<?php
/**
 * Created by PhpStorm.
 * User: zhuyujun
 * Date: 2017/10/24
 * Time: 15:21
 */

namespace App\Api\Service\Order\Controllers;


use App\Eloquent\Ygt\BuyersProduct;
use App\Eloquent\Ygt\Customer;
use App\Eloquent\Ygt\CustomerAddress;
use App\Eloquent\Ygt\CustomerOrderFeedback;
use App\Eloquent\Ygt\CustomerOrderPrice;
use App\Eloquent\Ygt\OrderListRelation;
use App\Eloquent\Ygt\OrderMaterialPurchaseMark;
use App\Eloquent\Ygt\OrderWage;
use App\Eloquent\Ygt\Plate;
use App\Eloquent\Ygt\PlateBranch;
use App\Eloquent\Ygt\PlateBranchColourplate;
use App\Eloquent\Ygt\ProcessOrdertype;
use App\Eloquent\Ygt\ProductCustomer;
use App\Eloquent\Ygt\ProductFields;
use App\Eloquent\Ygt\PurchaseMaterial;
use App\Eloquent\Ygt\SellerCompany;
use App\Eloquent\Ygt\User;
use App\Eloquent\Ygt\WaitPurchase;
use App\Eloquent\Ygt\Warehouse;
use Framework\BaseClass\Api\Controller;
use Illuminate\Http\Request;

use App\Eloquent\Ygt\Order;
use App\Eloquent\Ygt\OrderPre;
use App\Eloquent\Ygt\UserMessage;
use App\Eloquent\Ygt\OrderBasic;
use App\Eloquent\Ygt\OrdertypeCategory;
//use App\Eloquent\Ygt\OrderType;
use App\Eloquent\Ygt\OrderDistributionPre;
use App\Eloquent\Ygt\OrderDistribution;
use App\Eloquent\Ygt\OrderProcessPre;
use App\Eloquent\Ygt\OrderProcess;
use App\Eloquent\Ygt\OrderMaterial;
use App\Eloquent\Ygt\DepartmentUser;
use App\Eloquent\Ygt\Message;
use App\Eloquent\Ygt\OrderProcessCourse;
use App\Eloquent\Ygt\OrderProcessCourseGradation;
use App\Eloquent\Ygt\OrderMaterialCourse;
use App\Eloquent\Ygt\Privilege;
use App\Eloquent\Ygt\OrderReport;
use App\Eloquent\Ygt\OrderReportType;
use App\Eloquent\Ygt\OrderReportCell;
use App\Eloquent\Ygt\OrderFieldCompany;
//订单
use App\Eloquent\Ygt\CustomerOrderPre;
use App\Eloquent\Ygt\CustomerOrder;
use App\Eloquent\Ygt\CustomerOrderProcessPre;
use App\Eloquent\Ygt\CustomerOrderProcess;
use App\Eloquent\Ygt\CustomerOrderBilling;

use App\Eloquent\Ygt\ImgUpload;
use App\Eloquent\Ygt\ProcessFieldRelationSelect;
use App\Eloquent\Ygt\ProcessFieldRelationUnit;
use App\Eloquent\Ygt\ProcessField;
use  App\Eloquent\Ygt\Company;
use  App\Eloquent\Ygt\OrderPlate;
use  App\Eloquent\Ygt\CustomerInvoice;


use App\Eloquent\Province;
use App\Eloquent\City;
use App\Eloquent\Area;

use App\Eloquent\Ygt\Process;
use App\Eloquent\Ygt\Product;
use App\Eloquent\Ygt\Permission;
use App\Engine\OrderType;
use App\Engine\Stock;
use App\Engine\Func;
use App\Engine\Product as ProductEngine;
use App\Engine\Permission as PermissionEngine;
use App\Engine\OrderEngine;
use App\Engine\Plate as PlateEngine;
use App\Engine\Customer as CustomerEngine;


use App\Eloquent\Oa\FlowCustomerOrder;//新加，客户订单流程
use App\Engine\Buyers;


use Framework\Services\ImageUpload\imageProcess;
use Illuminate\Support\Facades\DB;


class IndexController extends Controller
{
    /**
     * Description:工单类型选择(选择要生成的产品)
     * User: zhuyujun
     * @return array
     */
    public function getOrderTypeAll()
    {
        $categoryId = request('category_id');
        $companyId = request('company_id');
//        header('Content-type: application/json');
        //获取所有工单类型的表
        //工单类型全部
        $userId = Func::getHeaderValueByName('userid');
        if ($userId) {
            $userInfo = DepartmentUser::getCurrentInfo($userId)->toArray();
            if (!$companyId) {
                $companyId = isset($userInfo['company_id']) ? $userInfo['company_id'] : '';
            }
        }


//        $orderTypeAll = OrderType::all();
        $orderTypeObj = new OrderType();
        $where = ['company_id' => $companyId];
        if ($categoryId) {
            $where['category_id'] = $categoryId;
        }

//        $orderTypeAll = $orderTypeObj->getData($where);
        $orderTypeAll = $orderTypeObj->getOrderTypeList($where);

        //图片路径增加域名
        $orderTypeList = [];
        foreach ($orderTypeAll as $tmpRow) {
            $orderTypeList[] = [
                '$imageUrl' => ImgUpload::getImgUrlById($tmpRow->img_id),
                '$typeTitle' => $tmpRow->title,
                '$typeFunctionName' => $tmpRow->id
            ];
        }

        $returnOrderTypeList = [
            'pageID' => 9,
            'data' => [
                '$list' => $orderTypeList
            ]
        ];

        return $returnOrderTypeList;
    }

    public function getOrderTypeCategory()
    {
        $companyId = request('company_id');

        $userId = Func::getHeaderValueByName('userid');
        $userInfo = DepartmentUser::getCurrentInfo($userId)->toArray();
        if (!$companyId) {
            $companyId = isset($userInfo['company_id']) ? $userInfo['company_id'] : '';
        }

        $where = [
            'company_id' => $companyId
        ];
        $ordertypeCategoryModel = new OrdertypeCategory();
        $list = $ordertypeCategoryModel->getData($where, 'id,cat_name');
        return $list;
    }

    /**
     * Description:提交工单类型
     * User: zhuyujun
     * @param Request $request
     * @return array
     */
    public function orderTypeSubmit(Request $request)
    {
        //获取传入数据
        $input = $request->all();
        //获取工单类型id
        //校验参数
        $rules = [
            'order_type' => 'required',
        ];
        $message = [
            'order_type.required' => '未选择工单类型'
        ];
        $this->validateRequestParameters($input, $rules, true, $message);


        //创建预生成工单&返回预生成工单id
        $orderPreRow = OrderPre::firstOrNew(['id' => '']);

        //工单号调整为正式生成工单时创建
//        $orderTitle = 'D' . time() . rand(0, 9) . rand(0, 9) . rand(0, 9) . rand(0, 9) . rand(0, 9) . rand(0, 9);
        $orderTitle = '';

        //用户id&企业id
        //$userId = request()->header('userid', 0);
        $userId = Func::getHeaderValueByName('userid');
        $userInfo = DepartmentUser::getCurrentInfo($userId)->toArray();
        $companyId = isset($userInfo['company_id']) ? $userInfo['company_id'] : '';

        $insertRow = [
            'order_type' => $input['order_type'],
            'order_title' => $orderTitle,
            'uid' => $userId,
            'company_id' => $companyId,
            'is_trash' => 1,//默认设置为该记录为可删除
        ];

        //获取客户订单信息
        $customerOrderId = isset($input['customer_order_id']) ? $input['customer_order_id'] : '';
        if ($customerOrderId) {//插入客户id和单位id
            $where = ['id' => $customerOrderId];
            $originalCustomerOrderRow = FlowCustomerOrder::where($where)->first()->toArray();
            $insertRow['customer_name'] = $originalCustomerOrderRow['customer_id'];
            $insertRow['field_name_23'] = $originalCustomerOrderRow['workplace'];
        }

        $orderPreRow->fill($insertRow);
        $orderPreRow->save();
        $orderId = $orderPreRow->id;

        return ['order_id' => $orderId];
    }

    /**
     * Description:工单创建-基础信息-选项参数获取
     * User: zhuyujun
     * @param Request $request
     * @return array
     */
    public function orderPreBaseInfo(Request $request)
    {
        //获取传入数据
        $input = $request->all();
        $input['copy_order_id'] = isset($input['copy_order_id']) ? $input['copy_order_id'] : '';//被复制的工单id 测试数据
        $pre_order_id = isset($input['pre_order_id']) ? $input['pre_order_id'] : '';//草稿箱工单id 测试数据

        $curOrderRow = OrderPre::where(['id' => $input['order_id']])->first()->toArray();
        $distributionOrderId = $input['order_id'];
        if ($pre_order_id !== '') {
            //草稿箱
            $curOrderRow = OrderPre::where(['id' => $pre_order_id])->first()->toArray();
            $orderId = $pre_order_id;
            $distributionOrderId = $orderId;
        } else if ($input['copy_order_id']) {
            //再来一单
            //校验参数
            $rules = [
                'order_id' => 'required',
            ];
            $message = [
                'order_id.required' => '未获取到到工单id'
            ];
            $this->validateRequestParameters($input, $rules, true, $message);
            $curOrderRow = Order::where(['id' => $input['copy_order_id']])->first()->toArray();
            //获取工单类型id
            $orderId = $input['order_id'];
            $distributionOrderId = $input['copy_order_id'];
        } else {
            //校验参数
            $rules = [
                'order_id' => 'required',
            ];
            $message = [
                'order_id.required' => '未获取到到工单id'
            ];
            $this->validateRequestParameters($input, $rules, true, $message);
            $orderId = $input['order_id'];
        }

        //工单基础信息字段，目前格式固定
//        $orderBaseFieldList = $this->orderBaseFieldList();
        $userId = Func::getHeaderValueByName('userid');
        $userInfo = DepartmentUser::getCurrentInfo($userId)->toArray();
        $companyId = isset($userInfo['company_id']) ? $userInfo['company_id'] : '';
        $orderBaseFieldList = OrderFieldCompany::getActiveFieldList($companyId);

        //添加默认值
        if (!empty($curOrderRow)) {
            foreach ($orderBaseFieldList as $key => $row) {
                if (isset($curOrderRow[$row['field_name']]) && $curOrderRow[$row['field_name']]) {
                    if ($row['field_type'] == 5) {//填写+单位选择 处理
                        $oldRow = $curOrderRow[$row['field_name']];
                        $oldRowArr = explode(',', $oldRow);
                        if (count($oldRowArr) > 1) {
                            $defaultValue = $oldRowArr[0];
                            $oldUnitTitle = $oldRowArr[1];
                            $oldUnitId = $this->getUnitIdByTitle($oldUnitTitle, $row['field_unit']);
                            if (!$oldUnitId) {
                                if (count($row['field_unit'])) {
                                    $oldUnitId = $row['field_unit'][0]['id'];
                                    $oldUnitTitle = $row['field_unit'][0]['title'];
                                } else {
                                    $oldUnitId = 0;
                                    $oldUnitTitle = '';
                                }
                            }

                            $orderBaseFieldList[$key]['default_value'] = $defaultValue;
                            $orderBaseFieldList[$key]['default_unit_id'] = $oldUnitId;
                            $orderBaseFieldList[$key]['default_unit_title'] = $oldUnitTitle;
                        }
                    } elseif ($row['field_type'] == 8) {//配送地址 处理
                        $customerAddressId = $curOrderRow[$row['field_name']];

                        $addressWhere = ['id' => $customerAddressId];
                        $customerAddress = \App\Eloquent\Ygt\BuyersAddress::withTrashed()->where($addressWhere)->first();
                        $customerAddressRow = [];
                        if ($customerAddress) {
                            $customerAddressRow = $customerAddress->toArray();
                        }

                        $showTitle = $customerAddressRow['province_name'] . $customerAddressRow['city_name'] . $customerAddressRow['area_name'];

                        $orderBaseFieldList[$key]['default_select_id'] = $customerAddressId;
                        $orderBaseFieldList[$key]['default_value'] = $showTitle;

                    } elseif ($row['field_type'] == 9) {//图片处理
                        $oldImgRow = $curOrderRow[$row['field_name']];
                        $imgIdList = explode(',', $oldImgRow);

                        $imgUrlListStr = '';
                        foreach ($imgIdList as $imgId) {
                            if (!trim($imgId)) {//过滤空格 图片id应该不会有0
                                continue;
                            }
                            $imgUrl = ImgUpload::getImgUrlById($imgId);
                            $imgUrlListStr .= $imgUrl . ',';
                        }

                        $imgUrlListStr = trim($imgUrlListStr, ',');
                        $orderBaseFieldList[$key]['default_img_id'] = $oldImgRow;
                        $orderBaseFieldList[$key]['default_img_url'] = $imgUrlListStr;
                    } elseif ($row['field_type'] == 17) {//版 处理
//                        $selectId = $curOrderRow[$row['field_name']];
//                        $orderBaseFieldList[$key]['default_select_id'] = $selectId;
//                        $plateRow = PlateEngine::getPlateInfo($selectId);
//
//                        if ($plateRow) {
////                            $tmpObj = \App\Eloquent\Ygt\BuyersProduct::where(['id'=>$plateRow['plate_name']])->first();
////                            if($tmpObj){
////                                $showTitle = $tmpObj['name'];
////                            }else{
////                                $showTitle = $plateRow['plate_name'];
////                            }
//                            $showTitle = $plateRow['plate_no'];
//                        } else {
//                            $showTitle = $curOrderRow[$row['field_name']];
//                        }
//
//                        $orderBaseFieldList[$key]['default_value'] = $showTitle;

                        //新的版数据
                        $tmpCreateOrderPlateRow = \App\Eloquent\Ygt\CreateOrderPlate::where(['id'=>$curOrderRow[$row['field_name']]])->first();
                        $plateInfo = json_decode(htmlspecialchars_decode($tmpCreateOrderPlateRow['content']), true);;
                        if(empty($plateInfo)){
                            $plateInfo = null;
                        }

                        $orderBaseFieldList[$key]['default_value'] = '';
                        $orderBaseFieldList[$key]['default_plate_list'] = $plateInfo;


                    } elseif ($row['field_type'] == 18) {//客户 处理
                        $selectId = $curOrderRow[$row['field_name']];
                        $orderBaseFieldList[$key]['default_select_id'] = $selectId;

                        $customerTitle = CustomerEngine::getNameById($selectId);
                        if ($customerTitle) {
                            $showTitle = $customerTitle;
                        } else {
                            $showTitle = $curOrderRow[$row['field_name']];
                        }
                        $orderBaseFieldList[$key]['default_value'] = $showTitle;
                    } elseif ($row['field_type'] == 19) {//单位 处理
                        $selectId = $curOrderRow[$row['field_name']];
                        $orderBaseFieldList[$key]['default_select_id'] = $selectId;

                        $buyersTitle = Buyers::getNameById($selectId);
                        if ($buyersTitle) {
                            $showTitle = $buyersTitle;
                        } else {
                            $showTitle = $curOrderRow[$row['field_name']];
                        }
                        $orderBaseFieldList[$key]['default_value'] = $showTitle;
                    } elseif ($row['field_type'] == 20) {//品名 处理
                        $selectId = $curOrderRow[$row['field_name']];
                        $orderBaseFieldList[$key]['default_select_id'] = $selectId;

                        $buyersProduct = \App\Eloquent\Ygt\BuyersProduct::where(['id' => $selectId])->first();

                        if ($buyersProduct) {
                            $showTitle = $buyersProduct['name'];
                        } else {
                            $showTitle = $curOrderRow[$row['field_name']];
                        }
                        $orderBaseFieldList[$key]['default_value'] = $showTitle;
                    } elseif ($row['field_type'] == 21) {//开票资料 处理
                        $selectId = $curOrderRow[$row['field_name']];
                        $orderBaseFieldList[$key]['default_select_id'] = $selectId;

                        $buyersInvoice = \App\Eloquent\Ygt\BuyersInvoice::where(['id' => $selectId])->first();

                        if ($buyersInvoice) {
                            $showTitle = $buyersInvoice['account_name'];
                        } else {
                            $showTitle = $curOrderRow[$row['field_name']];
                        }
                        $orderBaseFieldList[$key]['default_value'] = $showTitle;
                    }elseif ($row['field_type'] == 22) {//半成品展示


                        $tmpCreateOrderProcessProductRow = \App\Eloquent\Ygt\CreateOrderProcessProduct::where(['id'=>$curOrderRow[$row['field_name']]])->first();
                        $processProductInfo = json_decode(htmlspecialchars_decode($tmpCreateOrderProcessProductRow['content']), true);
                        if(empty($processProductInfo)){
                            $processProductInfo = null;
                        }

                        $orderBaseFieldList[$key]['default_value'] = '';
                        $orderBaseFieldList[$key]['default_process_product_list'] = $processProductInfo;


                    }

                    else {
                        $orderBaseFieldList[$key]['default_value'] = $curOrderRow[$row['field_name']];
                    }
                }

            }
        }

        $orderPreRow = OrderPre::where('id', $orderId)->first()->toArray();
        $orderType = $orderPreRow['order_type'];

        $processNum = OrderType::getAllOrderTypeProcess($orderType)->count();

        $related_feedback_num = $customerOrderFeedbackRowList = \App\Eloquent\Ygt\CustomerOrderFeedback
            ::leftJoin('ygt_customer_order','ygt_customer_order_feedback.customer_order_id','=','ygt_customer_order.id')
            ->where('ygt_customer_order.order_type','=',$orderType)
            ->count();

        return [
            'related_feedback_num'=>$related_feedback_num?sprintf("类似订单有反馈"):'',
            'process_title' => '基础信息',
            'order_base_field_list' => $orderBaseFieldList,
            'button_title' => '下一步',
            'create_order_title' => '创建工单（1/' . ($processNum + 1) . '）'
        ];
    }

    /**
     * Description:工单创建-基础信息-提交
     * User: zhuyujun
     * @param Request $request
     * @return array
     */
    public function orderPreBaseSubmit(Request $request)
    {
        //获取传入数据
        $input = $request->all();
        $input['is_draft'] = isset($input['is_draft']) ? $input['is_draft'] : 0;//是否存入草稿箱，是的话不校验数据

//        $orderBaseFieldList = $this->orderBaseFieldList();
        $userId = Func::getHeaderValueByName('userid');
        $userInfo = DepartmentUser::getCurrentInfo($userId)->toArray();
        $companyId = isset($userInfo['company_id']) ? $userInfo['company_id'] : '';
        $orderBaseFieldList = OrderFieldCompany::getActiveFieldList($companyId);
        //验证字段是必填还是选填 by zzy
        if (!$input['is_draft']) {
            $process_field_list = $orderBaseFieldList;
            $processFieldRules = [];
            $processFieldMessage = [];
            foreach ($process_field_list as $key => $val) {
                $isMust = $val['is_must'];
                if ($isMust == 1) {
                    $rulesName = 'required';
                    $fieldName = $val['field_name'];
                    $fieldTitle = $val['title'];
                    $fieldMsg = $fieldName . '.' . $rulesName;
                    $processFieldRules[$fieldName] = $rulesName;
                    $processFieldMessage[$fieldMsg] = $fieldTitle . '必填';

                    $inputValue = $input[$fieldName];
                    if (empty($inputValue)) {
                        xThrow(ERR_PARAMETER, $fieldTitle . '必填');
                    }
                }
            }
        }

//        //校验参数
//        $rules = [
//            'order_id' => 'required',
//        ];
//        $messages = [
//            'order_id.required' => '缺少工单id',
//        ];
//
//        $this->validateRequestParameters($input, $rules, true, $messages);

        //新加限制，产品数量必须填写数字
//        if (isset($input['product_num'])) {
//            $tmpArr = explode(',', $input['product_num']);
//            if (!is_numeric($tmpArr[0])) {
//                return [
//                    'code' => 1,
//                    'message' => '下单数量请填写数量'
//                ];
//            }
//        }
//        //交货日期不能晚于当天
//        if (isset($input['finished_date'])) {
//            if(date('Ymd') > date('Ymd',strtotime($input['finished_date']))){
//                return [
//                    'code' => 1,
//                    'message' => '交货日期不能晚于创建时间'
//                ];
//            }
//        }


        //数据入库
        //创建预生成工单&返回预生成工单id
        $orderId = $input['order_id'];
        $orderPreRow = OrderPre::firstOrNew(['id' => $orderId]);
        $orderType = $orderPreRow->order_type;

        //修改数据
        foreach ($orderBaseFieldList as $fieldRow) {
            if (isset($input[$fieldRow['field_name']])) {
                $tmpFieldName = $fieldRow['field_name'];

                if($fieldRow['field_type'] == 17){
                    $tmpObj = \App\Eloquent\Ygt\CreateOrderPlate::firstOrNew(['id'=>'']);
                    $tmpInsertRow = [
                        'type' => 1,
                        'relate_id' => $input['order_id'],
                        'field_name' => $tmpFieldName,
                        'content' => $input[$fieldRow['field_name']],
                    ];

                    $tmpObj->fill($tmpInsertRow);
                    $tmpObj->save();
                    $createOrderPlateId = $tmpObj->id;

                    $orderPreRow->$tmpFieldName = $createOrderPlateId;
                }else{
                    $orderPreRow->$tmpFieldName = $input[$fieldRow['field_name']];
                }
            }
        }


        $orderPreRow->status = 4;//工单状态 1-待接单 2-生产中 3-已完成 4-待派发状态
        $orderPreRow->is_trash = 0;//标记为不自动删除
        $orderPreRow->save();
//        return ['message'=>'提交成功'];
        $orderPreRow->id;

        //返回该工单类型的第一个工序
        $orderTypeObj = new OrderType();
//        $firstProcessId = $orderTypeObj->getFirstOneProcessId($orderType);
        $firstProcessRow = $orderTypeObj->getFirstStep($orderType);
        $firstProcessId = $firstProcessRow['process_id'];
        $firstOrdertypeProcessId = $firstProcessRow['id'];

        return [
            'process_id' => $firstProcessId,
            'ordertype_process_id' => $firstOrdertypeProcessId,
        ];
    }

    //工单创建-配送消息提交
    public function orderPreDistributionSubmit(Request $request)
    {
        //获取传入数据
        $input = $request->all();
        //校验参数
        $rules = [
            'order_id' => 'required',
        ];
        $messages = [
            'order_id.required' => '缺少工单id',
        ];

        $this->validateRequestParameters($input, $rules, true, $messages);

        //数据入库
        //创建预生成工单&返回预生成工单id
        $orderDistributionPreRow = OrderDistributionPre::firstOrNew(['order_id' => $input['order_id']]);
        $insertRow = [
            'order_id' => $input['order_id'],//关联的工单id
            'consignee' => $input['consignee'],//'收货人'
            'phone' => $input['phone'],//'电话'
            'province_id' => $input['province_id'],//'省-id'
            'province_name' => $input['province_name'],//'省-名称'
            'city_id' => $input['city_id'],//'市-id'
            'city_name' => $input['city_name'],//'市-名称'
            'area_id' => $input['area_id'],//'区-id'
            'area_name' => $input['area_name'],//'区-名称'
            'address' => $input['address'],//'详细地址'
        ];

        $orderDistributionPreRow->fill($insertRow);
        $orderDistributionPreRow->save();
        $orderDistributionPreRow->id;

//        return ['message'=>'提交成功'];
        return $orderDistributionPreRow->id;

    }

    /**
     * Description:正式生成工单数据
     * User: zhuyujun
     * @param $orderPreId
     */
    public function orderCreate($orderPreId)
    {

        $orderId = '';
        //基础信息
        //取出预生成数据
        $orderPre = OrderPre::where('id', $orderPreId);
        $orderPreRow = $orderPre->first()->toArray();

        //获取登陆用户信息
        $userId = $orderPreRow['uid'];
        $userInfo = DepartmentUser::getCurrentInfo($userId)->toArray();
        $companyId = isset($userInfo['company_id']) ? $userInfo['company_id'] : '';

        //存入正式数据
        $order = Order::firstOrNew(['id' => '']);
        unset($orderPreRow['id']);//不使用预生成表的id
        unset($orderPreRow['is_trash']);//删除草稿箱表独有的字段
        $orderPreRow['order_pre_id'] = $orderPreId;//存入对应的草稿箱

        ////生成工单号
        //获取该工单是当天的第几单
        $dayStartTime = strtotime(date('Ymd'));
        $intradayOrderCount = Order::withTrashed()->where([['created_at', '>=', $dayStartTime]])->get()->count();

        $ordeTitleIndex = '';
        $intradayOrderCount++;
        if ($intradayOrderCount < 10) {
            $ordeTitleIndex = sprintf('0%d', $intradayOrderCount);
        } else {
            $ordeTitleIndex = $intradayOrderCount;
        }
        $orderPreRow['order_title'] = 'GD' . date('ymd') . $ordeTitleIndex;

        $order->fill($orderPreRow);
        $order->save();
        $orderId = $order->id;
        $foreignKey = intval($order->customer_order_id);
        //删除预生成数据
        //基础信息
        $orderPre->delete();

        //数据加入到工单列表关联表中
        $orderPreRow['id'] = $orderId;
        OrderEngine::importMainOrder($orderPreRow);

////改为选择客户地址
//        //配送信息
//        //取出预生成数据
//        $orderDistributionPre = OrderDistributionPre::where('order_id', $orderPreId);
//        $orderDistributionPreRow = $orderDistributionPre->first();
//        if ($orderDistributionPreRow) {
//            $orderDistributionPreRow = $orderDistributionPreRow->toArray();
//            //存入正式数据
//            $orderDistribution = OrderDistribution::firstOrNew(['id' => '']);
//            $orderDistributionPreRow['order_id'] = $orderId;
//            $orderDistribution->fill($orderDistributionPreRow);
//            $orderDistribution->save();
//            $orderDistribution->id;
//            //删除预生成数据
//            $orderDistributionPre->delete();
//        }

        //工序信息处理
        $orderProcessPreList = OrderProcessPre::where('order_id', $orderPreId)->get();

        //获取第一道步骤涉及的工序
        $processFirstList = OrderType::getFirstProcessBag($orderPreRow['order_type'])->toArray();

        $allMaterialList = [];//保存所有材料信息
        foreach ($orderProcessPreList as $orderProcessPreObj) {
            $orderProcessPreRow = $orderProcessPreObj->toArray();
            //存入正式数据
            $orderProcess = OrderProcess::firstOrNew(['id' => '']);
            $orderProcessPreRow['order_id'] = $orderId;
            $orderProcessPreRow['status'] = 1;//工单工序默认状态为，1-待接单 2-确认开工（未领取材料） 3-已领取材料 4-确认完工
            $orderProcess->fill($orderProcessPreRow);
            $orderProcess->save();

            ////添加材料
            //获取字段信息
            $processFieldList = Process::getFieldListByProcessId($orderProcessPreRow['process_type']);
            foreach ($processFieldList as $processFieldRow) {
                $tmpFiledType = ProcessField::getFieldTypeByFieldName($processFieldRow['field_name'], $companyId);
                if ($tmpFiledType == 4) {//材料选择暂时不显示在
                    $materialList = explode(',', $orderProcessPreRow[$processFieldRow['field_name']]);
                    foreach ($materialList as $materialsId) {
                        //过滤空格
                        if (!trim($materialsId)) {
                            continue;
                        }

                        if (!in_array($materialsId, $allMaterialList)) {
                            $allMaterialList[] = $materialsId;
                        }

                        $orderMaterialObj = OrderMaterial::firstOrNew(['order_id' => $orderProcessPreRow['order_id'], 'process_type' => $orderProcessPreRow['process_type'], 'material_id' => $materialsId]);
                        //获取材料单价（集合材料取最近一个材料）
                        $materialPrice = \App\Engine\Material::getMaterialPrice($materialsId);


                        $orderMaterialRow = [
                            'order_id' => $orderProcessPreRow['order_id'],
                            'order_process_id' => $orderProcess['id'],
                            'process_type' => $orderProcessPreRow['process_type'],
                            'material_id' => $materialsId,
                            'company_id' => $companyId,
                            'price' => $materialPrice,
                        ];
                        $orderMaterialObj->fill($orderMaterialRow);
                        $orderMaterialObj->save();
                    }
                }

            }

            //删除预生成数据
            $orderProcessPreObj->delete();
        }

        $productIds = OrderMaterial::where('order_id', $orderId)->get()->pluck('material_id');

        $where = [];
        $where[] = ['whereRaw', 'number <= warning_number'];
        $where['id'] = ['in', $productIds];
        $productModel = new Product();
        $count = $productModel->getCount($where);

        ////不再在创建工单时推送消息，派发成功后给采购发消息 20180724 zhuyujun
//        if ($count >= 1) {
//            $products = $productModel->getData($where)->pluck('product_name')->toArray();
//
//            $products = implode('、', $products);
//
//            //给采购发送消息
//            $privilegeIds = Privilege::getPrivilegeIds($companyId, 8);
//
//            foreach ($privilegeIds as $val) {
//                $meesageContent = '工单号：' . $order['order_title'] . " 需采购" . $products . "等材料";
//                $data = [
//                    'company_id' => $companyId, 'privilege_id' => $val,
//                    'form_user_id' => $userId, 'to_user_id' => '',
//                    'foreign_key' => $foreignKey,
//                    'type' => 10, 'type_id' => $orderId,
//                    'title' => $orderPreRow['order_title'], 'content' => $meesageContent
//                ];
//                UserMessage::sendCustomerOrderMessage($data);
//            }
//        }

        //增加订单类型使用次数
        $orderTypeId = $orderPreRow['order_type'];
        OrderType::incrementUseNum($orderTypeId);

        //如果是由订单转工单的，将最新的工单信息补充到订单信息中
        $customerOrderId = $orderPreRow['customer_order_id'];
        if ($customerOrderId) {
            //补充覆盖订单基础信息
            $curOrderInfo = Order::where(['id' => $orderId])->first()->toArray();

            //不再更新工单信息到订单中 20180628 朱雨骏
//            //过滤不需要覆盖的字段
//            unset($curOrderInfo['id']);
//            unset($curOrderInfo['order_pre_id']);
//            unset($curOrderInfo['created_at']);
//            unset($curOrderInfo['updated_at']);
//            unset($curOrderInfo['deleted_at']);
//            unset($curOrderInfo['order_title']);
//            unset($curOrderInfo['uid']);
//            unset($curOrderInfo['customer_order_id']);
//            unset($curOrderInfo['product_num']);//按需求不覆盖数量 20180627 zhuyujun
//            $customerOrderObj = CustomerOrder::where(['id' => $customerOrderId])->first();
//            $customerOrderObj->fill($curOrderInfo);
//            $customerOrderObj->save();

            //补充覆盖订单工序信息
            $curOrderProcessList = OrderProcess::where(['order_id' => $orderId])->get()->toArray();
            foreach ($curOrderProcessList as $curOrderProcessRow) {
                $orderTypeProcessId = $curOrderProcessRow['ordertype_process_id'];


                //不再更新工单信息到订单中 20180628 朱雨骏
//                //过滤不需要覆盖的字段
//                unset($curOrderProcessRow['id']);
//                unset($curOrderProcessRow['order_id']);
//                unset($curOrderProcessRow['uid']);
//                unset($curOrderProcessRow['estimated_time_day']);
//                unset($curOrderProcessRow['estimated_time_hour']);
//                unset($curOrderProcessRow['estimated_time_minute']);
//                unset($curOrderProcessRow['start_time']);
//                unset($curOrderProcessRow['status']);
//                $tmpCustomerProcessOrderObj = CustomerOrderProcess::where(['order_id' => $customerOrderId, 'ordertype_process_id' => $orderTypeProcessId])->first();
//                $tmpCustomerProcessOrderObj->fill($curOrderProcessRow);
//                $tmpCustomerProcessOrderObj->save();

            }
        }


        //修改订单状态
        $tmpCustomerOrderObj = CustomerOrder::where(['id' => $customerOrderId])->first();
        $tmpCustomerOrderObj->status = 2;//待接单状态
        $tmpCustomerOrderObj->save();


        //发送消息给发货员 zhuyujun 20180726
        $privilegeIdList = \App\Engine\OrderEngine::getPrivilegeByNode($companyId, 14);
        foreach ($privilegeIdList as $privilegeId) {
            if ($privilegeId) {
                $data = [
                    'company_id' => $companyId,
                    'privilege_id' => $privilegeId,
                    'form_user_id' => $userId,
                    'to_user_id' => '',
                    'foreign_key' => $foreignKey,
                    'type' => 34,//type待定
                    'type_id' => $orderId,
                    'title' => $orderPreRow['order_title'],
                    'content' => '有新的工单创建了'
                ];
                UserMessage::sendCustomerOrderMessage($data);
            }
        }


        return [
            'order_id' => $orderId,
            'order_title' => $order['order_title'],
        ];


//        //创建工单时，发送消息给采购员，提示采购员所需的材料及库存 -- 已调整，不再发送材料信息
    }


    /**
     * Description:获取省市区联动数据
     * User: zhuyujun
     * @param Request $request
     * @return mixed
     */
    public function getCityList(Request $request)
    {
        //获取传入数据
        $input = $request->all();
        //获取工单类型id
        $type = isset($input['type']) ? $input['type'] : '';
        $provinceId = isset($input['provinceId']) ? $input['provinceId'] : '';
        $cityId = isset($input['cityId']) ? $input['cityId'] : '';

        if ($type == 1) {//获取省列表
            $provinceList = Province::all();
            foreach ($provinceList as $row) {
                $row->cid = $row->provinceID;
                $row->cat_name = $row->province;
            }
            $provinceList = $provinceList->toArray();
            return $provinceList;
        } elseif ($type == 2) {//获取市列表
            $cityList = City::where('fatherID', $provinceId)->get();
            foreach ($cityList as $row) {
                $row->cid = $row->cityID;
                $row->cat_name = $row->city;
                $row->aid = $row->cityID;
                $row->subject = $row->city;
            }
            $cityList = $cityList->toArray();
            return $cityList;
        } elseif ($type == 3) {//获取区列表
            $areaList = Area::where('fatherID', $cityId)->get();
            foreach ($areaList as $row) {
                $row->cid = $row->areaID;
                $row->cat_name = $row->area;
                $row->aid = $row->areaID;
                $row->subject = $row->area;
            }
            $areaList = $areaList->toArray();
            return $areaList;
        } elseif ($type == 4) {//获取省市区列表，ios环境使用
            $provinceList = Province::all()->toArray();
            $cityList = City::all()->toArray();
            $areaList = Area::all()->toArray();
            $zone = [];
            foreach ($provinceList as $key => $province) {
                $city_arr = [];
                foreach ($cityList as $k => $city) {
                    if ($city['fatherID'] == $province['provinceID']) {
                        foreach ($areaList as $kk => $area) {
                            if ($area['fatherID'] == $city['cityID']) {
                                $city['arealist'][] = $area;
                            }
                        }
                        $city_arr[] = $city;
                    }
                }
                $province['citylist'] = $city_arr;
                $zone[] = $province;

            }
            return $zone;
        }
    }

    private function distributeData($orderList)
    {

        $returnOrderList = [];
        $dataList = [];
        foreach ($orderList as $orderRow) {
            $type = $orderRow['type'];//工单类型 1-主工单 2-工序管理员工单 3-查看权限用户的工序工单 4-员工工单
            $status = $orderRow['status'];//不同类型工单，状态有所不同
            $orderRowContent = unserialize($orderRow['content']);


            //追加工单进度情况
            $progressBar = [];//各工艺进度条
            $mainOrderId = $mainOrderStatus = '';
            if($type == 1){
                $mainOrderStatus = $status;
                $mainOrderId = $orderRow['relate_id'];

                //进度条
                $tmpOrderProcessList = \App\Eloquent\Ygt\OrderProcess::where(['order_id'=>$mainOrderId])->get();

                //获取工单对应的所有工序
                $tmpOrderProcessList = \App\Engine\OrderType::getAllOrderTypeProcess($orderRowContent['order_type'])->toArray();
                foreach ($tmpOrderProcessList as $tmpProcessId) {
                    $tmpOrderProcessRow = OrderProcess::where(['order_id' => $orderRowContent['id'], 'process_type' => $tmpProcessId])->first();
                    if (!$tmpOrderProcessRow) {
                        continue;
                    }
//                }

//                foreach ($tmpOrderProcessList as $tmpOrderProcessRow){
                    //工序名称
                    $tmpProcessTitle = \App\Eloquent\Ygt\Process::getOneValueById($tmpOrderProcessRow['process_type'], 'title');

                    //工序完成度
                    $tmpOrderProcessNeedNum =\App\Engine\OrderEngine::getOrderPorcessNeedNum($tmpOrderProcessRow['process_type'],$orderRowContent);//需完成数量
                    $tmpRadio = 0;
                    if($tmpOrderProcessNeedNum){
                        $tmpRadio = $tmpOrderProcessRow['completed_number'] / $tmpOrderProcessNeedNum;
                    }

//                    if($tmpRadio > 1){
//                        $tmpRadio = 1;
//                    }

                    $tmpRadio = sprintf('%.2f',$tmpRadio);
                    $tmpType = \App\Engine\OrderEngine::getOrderRadioType($tmpRadio);
                    $progressBar[] = [
                        'type' => $tmpType,
                        'radio' => $tmpRadio,
                        'title' => $tmpProcessTitle,
                    ];
                }


            }elseif($type == 2 || $type == 3){
                //获取主工单状态&ID
                $tmpOrderProcessId = $orderRow['relate_id'];
//                $mainOrderRow = \App\Eloquent\Ygt\OrderProcess::leftJoin('ygt_order','ygt_order.id','ygt_order_process.order_id')->where(['ygt_order_process.id'=>$tmpOrderProcessId])->select(
//                    'ygt_order.id',
//                    'ygt_order.status'
//                )->first();
//                $mainOrderId = $mainOrderRow['id'];
//                $mainOrderStatus = $mainOrderRow['status'];

                //进度条
                $tmpOrderProcessList = \App\Eloquent\Ygt\OrderProcess::where(['id'=>$tmpOrderProcessId])->get();
                foreach ($tmpOrderProcessList as $tmpOrderProcessRow){
                    //工序名称
                    $tmpProcessTitle = \App\Eloquent\Ygt\Process::getOneValueById($tmpOrderProcessRow['process_type'], 'title');

                    //工序完成度
                    $tmpOrderProcessNeedNum =\App\Engine\OrderEngine::getOrderPorcessNeedNum($tmpOrderProcessRow['process_type'],$orderRowContent);//需完成数量
                    $tmpRadio = 0;
                    if($tmpOrderProcessNeedNum){
                        $tmpRadio = $tmpOrderProcessRow['completed_number'] / $tmpOrderProcessNeedNum;
                    }

                    $tmpRadio = sprintf('%.2f',$tmpRadio);
                    $tmpType = \App\Engine\OrderEngine::getOrderRadioType($tmpRadio);
                    $progressBar[] = [
                        'type' => $tmpType,
                        'radio' => $tmpRadio,
                        'title' => $tmpProcessTitle,
                    ];
                }



            }elseif($type == 4){
                //获取主工单状态&ID
                $tmpOrderProcessCourseId = $orderRow['relate_id'];
                $tmpOrderProcessId = \App\Eloquent\Ygt\OrderProcessCourse::where(['id'=>$tmpOrderProcessCourseId])->first()->order_process_id;
//                $mainOrderRow = \App\Eloquent\Ygt\OrderProcess::leftJoin('ygt_order','ygt_order.id','ygt_order_process.order_id')->where(['ygt_order_process.id'=>$tmpOrderProcessId])->select(
//                    'ygt_order.id',
//                    'ygt_order.status'
//                )->first();
//                $mainOrderId = $mainOrderRow['id'];
//                $mainOrderStatus = $mainOrderRow['status'];

                //进度条
                $tmpOrderProcessList = \App\Eloquent\Ygt\OrderProcess::where(['id'=>$tmpOrderProcessId])->get();
                foreach ($tmpOrderProcessList as $tmpOrderProcessRow){
                    //工序名称
                    $tmpProcessTitle = \App\Eloquent\Ygt\Process::getOneValueById($tmpOrderProcessRow['process_type'], 'title');

                    //工序完成度
                    $tmpOrderProcessNeedNum =\App\Engine\OrderEngine::getOrderPorcessNeedNum($tmpOrderProcessRow['process_type'],$orderRowContent);//需完成数量
                    $tmpRadio = 0;
                    if($tmpOrderProcessNeedNum){
                        $tmpRadio = $tmpOrderProcessRow['completed_number'] / $tmpOrderProcessNeedNum;
                    }

                    $tmpRadio = sprintf('%.2f',$tmpRadio);
                    $tmpType = \App\Engine\OrderEngine::getOrderRadioType($tmpRadio);
                    $progressBar[] = [
                        'type' => $tmpType,
                        'radio' => $tmpRadio,
                        'title' => $tmpProcessTitle,
                    ];
                }
            }


            //过滤掉工艺名称的工序名称
            $tmpOrderTypeTitle = \App\Engine\OrderType::getOneValueById($orderRowContent['order_type'], 'title');//工艺名称
            $tmpDealList = [];
            foreach ($progressBar as $tmpKey => $tmpRow){
                $tmpRow['title'] = str_replace([$tmpOrderTypeTitle."•",$tmpOrderTypeTitle],'',$tmpRow['title']);
                $tmpDealList[$tmpKey] = $tmpRow;
            }
            $progressBar = $tmpDealList;

//            //待接单
//            $progressBar = [
//                'type' => 1,
//                'radio' => 0,
//                'title' => '未知状态',
//            ];
//            if($mainOrderStatus == 1){
//                $progressBar = [
//                    'type' => 1,
//                    'radio' => 0,
//                    'title' => '待接单',
//                ];
//            };
//            if($mainOrderStatus == 101){
//                $progressBar = [
//                    'type' => 2,
//                    'radio' => 0,
//                    'title' => '待开工',
//                ];
//            }
//
//            if($mainOrderStatus == 2){
//                //工序数量&完成数量
//                $orderProcessNum = $orderProcessFinishNum = $radio = 0;
//                $tmpOrderProcessList = \App\Eloquent\Ygt\OrderProcess::where(['order_id'=>$mainOrderId])->get();
//                $title = '';//提示文字
//                foreach ($tmpOrderProcessList as $tmpOrderProcessRow){
//                    $orderProcessNum ++;
//
//                    //未接单的不处理
//                    if($tmpOrderProcessRow['status'] == 1){
//                        continue;
//                    }
//
//                    if($tmpOrderProcessRow['status'] == 2){
//                        //获取工序名称
//                        $processTitle = \App\Eloquent\Ygt\Process::getOneValueById($tmpOrderProcessRow['process_type'], 'title');
//                        $title = "[{$processTitle}]已接单";
//                    }
//
//                    if($tmpOrderProcessRow['status'] == 101){
//                        //获取工序名称
//                        $processTitle = \App\Eloquent\Ygt\Process::getOneValueById($tmpOrderProcessRow['process_type'], 'title');
//                        $title = "[{$processTitle}]待开工";
//                    }
//
//                    if($tmpOrderProcessRow['status'] == 3){
//                        //获取工序名称
//                        $processTitle = \App\Eloquent\Ygt\Process::getOneValueById($tmpOrderProcessRow['process_type'], 'title');
//                        $title = "[{$processTitle}]已开工";
//                    }
//
//                    if($tmpOrderProcessRow['status'] == 4){
//                        $orderProcessFinishNum ++;
//                        //获取工序名称
//                        $processTitle = \App\Eloquent\Ygt\Process::getOneValueById($tmpOrderProcessRow['process_type'], 'title');
//                        $title = "[{$processTitle}]已完工";
//                    }
//                }
//
//
//                if(!$title){
//                    $title = '待接单';
//                }
//
//                if($orderProcessNum){
//                    $radio = $orderProcessFinishNum / $orderProcessNum;
//                    $radio = sprintf('%.2f',$radio);
//                }
//
//                $progressBar = [
//                    'type' => 2,
//                    'radio' => $radio,
//                    'title' => $title,
//                ];
//            }
//
//
//            if($mainOrderStatus == 3){
//                $progressBar = [
//                    'type' => 3,
//                    'radio' => 1,
//                    'title' => '已完工',
//                ];
//            }






            //获取生产实例图
            $productionCaseDiagram = \App\Engine\OrderEngine::getOrderFiledValueTrue($orderRowContent['production_case_diagram'], 9);


            //处理字段
            $orderRowContent = \App\Engine\OrderEngine::dealOrderFiled($orderRowContent);

            //订单创建时间（派发时间）
            $orderCreateTime = $orderRow['order_create_time'];
            if ($orderCreateTime) {
                $orderCreateTime = date('Y-m-d', $orderCreateTime);
            }

            //获取工序类型名称
            $orderTypeTitle = OrderType::getOneValueById($orderRowContent['order_type'], 'title');


            //工单列表不同类型相同字段，统一管理
            $productName = \App\Engine\OrderEngine::getOrderFiledValueTrue($orderRowContent['product_name'], 20);

            //增加图片ID
            $imgId = $orderRowContent['production_case_diagram'];

            $orderRowContent['order_title'] = \App\Engine\Common::changeSnCode($orderRowContent['order_title']);
            $commonArr = [
                '$customer_title' => '单位名称',//工单列表展示字段
                '$product_title' => '品名',//工单列表展示字段
                '$order_title' => '单号',//工单列表展示字段
                '$customer_name' => isset($orderRowContent['field_name_23']) ? $orderRowContent['field_name_23'] : '',//新加字段客户
                '$product_name' => isset($productName) ? $productName : '',//新加字段品名
                '$order_title_value' => $orderRowContent['order_title'],//新加字段单号
                '$firstPropertyName' => '成品规格',
                '$secondPropertyName' => '数量',
                '$thirdPropertyName' => '交货日期',
                '$thirdPropertyValue' => $orderRowContent['finished_date'],
                '$secondPropertyValue' => $orderRowContent['product_num'],
                '$firstPropertyValue' => isset($orderRowContent['finished_specification']) ? $orderRowContent['finished_specification'] : '',
                '$productionCaseDiagram' => $productionCaseDiagram,
                '$productOrderTimeValue' => $orderCreateTime,
                '$orderTypeTitle' => $orderTypeTitle,
                '$orderNumberValue' => $orderTypeTitle,
                '$orderTimeValue' => $orderRowContent['finished_date'],
                '$relate_id' => $orderRow['relate_id'],
                'img_id' => $imgId,
                'progress_bar' => $progressBar,
            ];

            if ($type == 1) {//1-主工单
                if ($status == 1) {//待接单
                    $tmpArr = [
                        'idName' => 5,
                        '$itemFunctionName' => 'mangerDoneCellFunction' . $orderRow['relate_id'],
                        '$statusCode' => $status,//新增订单状态值
                        '$orderStatus' => '待接单',
                        '$statusColor' => 'FFB401',
                    ];
                    $dataList[] = array_merge($commonArr, $tmpArr);

                } elseif ($status == 101) {//待开工
                    $tmpArr = [
                        'idName' => 3,
                        '$itemFunctionName' => 'mangerDoneCellFunction' . $orderRow['relate_id'],
                        '$statusCode' => $status,//新增订单状态值
                        '$orderStatus' => '待开工',
                        '$statusColor' => 'FFB401',
                    ];
                    $dataList[] = array_merge($commonArr, $tmpArr);
                } elseif ($status == 2) {//生产中
                    $tmpArr = [
                        'idName' => 3,
                        '$itemFunctionName' => 'mangerDoneCellFunction' . $orderRow['relate_id'],
                        '$statusCode' => $status,//新增订单状态值
                        '$orderStatus' => '生产中',
                        '$statusColor' => 'FE7E57',
                    ];
                    $dataList[] = array_merge($commonArr, $tmpArr);
                } elseif ($status == 3) {//已完工
                    $tmpArr = [
                        'idName' => 6,
                        '$itemFunctionName' => 'mangerDoneCellFunction' . $orderRow['relate_id'],
                        '$orderSureName' => 'orderSure' . $orderRow['relate_id'],
                        '$statusCode' => $status,//新增订单状态值
                        '$orderStatus' => '已完成',
                        '$statusColor' => '04C9B3',
                    ];
                    $dataList[] = array_merge($commonArr, $tmpArr);
                } elseif ($status == 4) {//待派发
                    continue;//未派发工单另外处理
                }
            } elseif ($type == 2) {//2-工序管理员工单
                if ($status == 1) {//待接单
                    $tmpArr = [
                        'idName' => 1,
                        '$itemFunctionName' => 'productdirectorWaitCellFunction' . $orderRow['relate_id'],
                        '$orderSureName' => 'productdirectorOrderSure' . $orderRow['relate_id'],
                        '$orderSureBgImage' => 'orderCellStatusButton.png',
                        '$statusCode' => $status,//新增订单状态值
                        '$orderStatus' => '待接单',
                        '$statusColor' => 'FFB401',
                    ];
                    $dataList[] = array_merge($commonArr, $tmpArr);
                } elseif ($status == 2) {//生产中-未分配工单
                    $tmpArr = [
                        'idName' => 3,
                        '$itemFunctionName' => 'productdirectorWaitCellFunction' . $orderRow['relate_id'],
                        '$statusCode' => $status,//新增订单状态值
                        '$orderStatus' => '待分配',
                        '$statusColor' => 'FFB401',//待接单,待分派,待开工
                    ];
                    $dataList[] = array_merge($commonArr, $tmpArr);
                } elseif ($status == 101) {//待开工
                    $tmpArr = [
                        'idName' => 3,
                        '$itemFunctionName' => 'productdirectorproductIngCellFunction' . $orderRow['relate_id'],
                        '$statusCode' => $status,//新增订单状态值
                        '$orderStatus' => '待开工',
                        '$statusColor' => 'FFB401',//待接单,待分派,待开工
                    ];
                    $dataList[] = array_merge($commonArr, $tmpArr);
                } elseif ($status == 3) {//生产中-已分配工单
                    $tmpArr = [
                        'idName' => 3,
                        '$itemFunctionName' => 'productdirectorproductIngCellFunction' . $orderRow['relate_id'],
                        '$statusCode' => $status,//新增订单状态值
                        '$orderStatus' => '生产中',
                        '$statusColor' => 'FE7E57',//生产中
                    ];
                    $dataList[] = array_merge($commonArr, $tmpArr);
                } elseif ($status == 4) {//已完工
                    $tmpArr = [
                        'idName' => 4,
                        '$itemFunctionName' => 'productdirectorDoneCellFunction' . $orderRow['relate_id'],
                        '$orderSureName' => 'orderSure' . $orderRow['relate_id'],
                        '$statusCode' => $status,//新增订单状态值
                        '$orderStatus' => '已完成',
                        '$statusColor' => '04C9B3',//已完成
                    ];
                    $dataList[] = array_merge($commonArr, $tmpArr);;
                }
            } elseif ($type == 3) {//3-查看权限用户的工序工单
                $orderStatusArr = [
                    '1' => '待接单',
                    '2' => '待分派',
                    '3' => '生产中',
                    '4' => '已完成',
                    '101' => '待开工',
                ];
                $orderStatusColorArr = [
                    '1' => 'FFB401',
                    '2' => 'FFB401',
                    '3' => 'FE7E57',
                    '4' => '04C9B3',
                    '101' => 'FFB401',
                ];

                if (!isset($orderStatusArr[$status])) {//异常处理
                    $orderStatusArr[$status] = '异常状态';
                    $orderStatusColorArr[$status] = 'FFB401';
                }

                $tmpArr = [
                    'idName' => 4,
                    '$itemFunctionName' => 'productdirectorDoneCellFunction' . $orderRow['relate_id'],
                    '$orderSureName' => 'orderSure' . $orderRow['relate_id'],
                    '$statusCode' => $status,//新增订单状态值
                    '$orderStatus' => $orderStatusArr[$status],
                    '$statusColor' => $orderStatusColorArr[$status],//待接单,待分派,待开工
                ];
                $dataList[] = array_merge($commonArr, $tmpArr);;
            } elseif ($type == 4) {//4-员工工单

                if ($status == 1) {//待接单
                    $tmpArr = [
                        'idName' => 1,
                        '$itemFunctionName' => 'waitCellFunction' . $orderRow['relate_id'],
                        '$orderSureName' => 'orderSure' . $orderRow['relate_id'],
                        '$orderSureBgImage' => 'draftsOrderCellStatusButton.png',
                        '$statusCode' => $status,//新增订单状态值
                        '$orderStatus' => '待开工',
                        '$statusColor' => 'FFB401',//待接单,待分派,待开工
                    ];
                    $dataList[] = array_merge($commonArr, $tmpArr);;
                } elseif ($status == 2) {//生产中-未领取材料
                    $tmpArr = [
                        'idName' => 3,
                        '$itemFunctionName' => 'productIngNoneGetFunction' . $orderRow['relate_id'],
                        '$statusCode' => $status,//新增订单状态值
                        '$orderStatus' => '待领料',
                        '$statusColor' => 'FFB401',//待接单,待分派,待开工
                    ];
                    $dataList[] = array_merge($commonArr, $tmpArr);;
                } elseif ($status == 3) {//生产中-已领取材料
                    $tmpArr = [
                        'idName' => 3,
                        '$itemFunctionName' => 'productIngNoneDoneFunction' . $orderRow['relate_id'],
                        '$statusCode' => $status,//新增订单状态值
                        '$orderStatus' => '生产中',
                        '$statusColor' => 'FE7E57',//生产中
                    ];
                    $dataList[] = array_merge($commonArr, $tmpArr);;
                } elseif ($status == 4) {//已完工
                    $tmpArr = [
                        'idName' => 4,
                        '$itemFunctionName' => 'doneCellFunction' . $orderRow['relate_id'],
                        '$orderSureName' => 'orderSure' . $orderRow['relate_id'],
                        '$statusCode' => $status,//新增订单状态值
                        '$orderStatus' => '已完成',
                        '$statusColor' => '04C9B3',//已完成
                    ];
                    $dataList[] = array_merge($commonArr, $tmpArr);;
                }
            }
        }

        $returnOrderList['pageID'] = 0;
        $returnOrderList['data']['$tableviewSource'] = $dataList;

        return $returnOrderList;
    }

    /**
     * @return array
     * 客户订单列表
     */
    public function getCustomerOrderList()
    {

        $customerId = request('customer_id');
        $isAll = request('is_all');
        $params = [
            'customer_id' => $customerId
        ];


        $userId = Func::getHeaderValueByName('userid');

        //判断用户是否为管理员
        $userInfo = DepartmentUser::getCurrentInfo($userId)->toArray();
        $companyId = isset($userInfo['company_id']) ? $userInfo['company_id'] : '';


        //获取订单信息
        ////下单人和销售员展示不同的订单
        //下单人
        $isManager = \App\Eloquent\Ygt\Privilege::getAppnodeId($userInfo['privilege_id'], 1);//是否为下单人（管理员权限）
        //销售
        $isSeller =  \App\Eloquent\Ygt\Privilege::getAppnodeId($userInfo['privilege_id'], 13);//是否为销售

        if (!$isAll) {
            $where['customer_name'] = $customerId;
        }

        $where['company_id'] = $companyId;

        $customerOrderList = CustomerOrder::where($where)->orderby('updated_at', 'desc')->get();


        $tmpOrderList = [];
        foreach ($customerOrderList as $tmpCustomerOrderRow) {

            //获取生产实例图
            $productionCaseDiagramIds = isset($tmpCustomerOrderRow['production_case_diagram']) ? $tmpCustomerOrderRow['production_case_diagram'] : '';
            if ($productionCaseDiagramIds) {
                $tmpArr = explode(',', $productionCaseDiagramIds);
                $productionCaseDiagramId = reset($tmpArr);
                $productionCaseDiagram = ImgUpload::getImgUrlById($productionCaseDiagramId);
                if (!$productionCaseDiagram) {//未获取到id对应的图片
                    $productionCaseDiagram = env('APP_URL') . '/assets/mobile/common/images/order_list_default.png';
                }

            } else {
                $productionCaseDiagram = env('APP_URL') . '/assets/mobile/common/images/order_list_default.png';
            }

            //订单创建时间（派发时间）
            $tmpArr = $tmpCustomerOrderRow->toArray();
            $orderCreateTime = $tmpArr['created_at'];

            if ($orderCreateTime) {
                $orderCreateTime = date('Y-m-d', $orderCreateTime);
                if ($orderCreateTime < 631152000) {//过滤1970的情况
                    $orderCreateTime = '';
                }
            } else {
                $orderCreateTime = '';
            }

            //订单字段处理
            $tmpCustomerOrderRow = \App\Engine\OrderEngine::dealOrderFiled($tmpCustomerOrderRow);


            //订单状态
            $statusColor = 'FE7E57';//默认颜色
            if (!$tmpCustomerOrderRow['is_deal_price']) {
                //订单价格未确认
                $customerOrderPriceObj = \App\Eloquent\Ygt\CustomerOrderPrice::where(['customer_order_id' => $tmpCustomerOrderRow['id']])->first();
                if ($customerOrderPriceObj) {
                    $customerOrderPriceStatus = $customerOrderPriceObj->status;
                    //针对单下单人权限，不显示待报价状态订单
                    if($isManager && !$isSeller){
                        if($customerOrderPriceStatus == 1){
                            continue;
                        }
                    }

                    $customerOrderPriceStatusArr = config('order.customer_order_price_status_list');
                    if (isset($customerOrderPriceStatusArr[$customerOrderPriceStatus])) {
                        $orderStatus = $customerOrderPriceStatusArr[$customerOrderPriceStatus]['txt'];
                        $statusColor = $customerOrderPriceStatusArr[$customerOrderPriceStatus]['color'];
                    } else {
                        $orderStatus = '';
                    }
                    $type = 2;
                } else {
                    $orderStatus = '';
                    $type = 1;
                }

            } else {
                //订单价格已确认
                $customerOrderStatusList = config('order.customer_order_status_list');
                if (isset($customerOrderStatusList[$tmpCustomerOrderRow['status']])) {
                    $orderStatus = $customerOrderStatusList[$tmpCustomerOrderRow['status']]['txt'];
                    $statusColor = $customerOrderStatusList[$tmpCustomerOrderRow['status']]['color'];
                }

                $type = 1;
            }


            //针对单下单人权限 强制更改订单状态文字
//            if($isManager && !$isSeller){
//                if(in_array($tmpCustomerOrderRow['status'],[1,2,3])){
//                    $orderStatus = '';
//                }
//
//                if(in_array($tmpCustomerOrderRow['status'],[5,6])){
//                    $orderStatus = '已报价';
//                }
//            }

            if($tmpCustomerOrderRow['is_file'] == 1){
                $orderStatus = '已归档';
            }

            //获取工序类型名称
            $orderTypeTitle = OrderType::getOneValueById($tmpCustomerOrderRow['order_type'], 'title');

            $productName = \App\Engine\OrderEngine::getOrderFiledValueTrue($tmpCustomerOrderRow['product_name'], 20);

            //追加图片ID
            $imgId = $tmpCustomerOrderRow['production_case_diagram'];

            $tmpCustomerOrderRow['order_title'] = \App\Engine\Common::changeSnCode($tmpCustomerOrderRow['order_title']);
            $tmpOrderList[] = [
                'ordertype_title' => '工艺:',//工单列表展示字段
                'order_title' => '单号:',//工单列表展示字段
                'unit_name' => isset($tmpCustomerOrderRow['field_name_23']) ? $tmpCustomerOrderRow['field_name_23'] : '',//新加字段单位
                'product_name' => isset($productName) ? $productName : '',//新加字段品名
                'order_title_value' => $tmpCustomerOrderRow['order_title'],//新加字段单号
                'firstPropertyName' => '成品规格',
                'secondPropertyName' => '数量',
                'thirdPropertyName' => '交货日期',
                'thirdPropertyValue' => $tmpCustomerOrderRow['finished_date'],
                'secondPropertyValue' => $tmpCustomerOrderRow['product_num'],
                'firstPropertyValue' => isset($tmpCustomerOrderRow['finished_specification']) ? $tmpCustomerOrderRow['finished_specification'] : '',
                'productionCaseDiagram' => $productionCaseDiagram,
                'productOrderTimeValue' => $orderCreateTime,
                'orderTypeTitle' => $orderTypeTitle,
                'relate_id' => $tmpCustomerOrderRow['id'],
                'orderStatus' => $orderStatus,
                'statusColor' => $statusColor,
                'type' => $type,
                'img_id' => $imgId,
            ];
        }

        $orderList = $tmpOrderList;

        $re['pageID'] = 0;
        $re['data']['tableviewSource'] = $orderList;

        return $re;
    }

    /**
     * @return array
     * 版工单列表
     */
    public function getPlateOrderList()
    {

        $plateId = request('plate_id');
        $params = [
            'plate_id' => $plateId
        ];

        $rules = [
            'plate_id' => 'required|integer',
        ];
        $this->validateRequestParameters($params, $rules);

        $userId = Func::getHeaderValueByName('userid');

        //判断用户是否为管理员
        $userInfo = DepartmentUser::getCurrentInfo($userId)->toArray();
        $companyId = isset($userInfo['company_id']) ? $userInfo['company_id'] : '';

//        $where = [['company_id', '=', $companyId], ['plate_id', '=', $plateId]];
        $where = [['plate_id', '=', $plateId]];
        $orderPlateList = OrderPlate::where($where)->orderBy('id', 'desc')->get();
        $allCount = $orderPlateList->count();
        $tmpArr = [];

        foreach ($orderPlateList as $orderPlateRow) {
            //获取工单详情
            $tmpOrderId = $orderPlateRow['order_id'];
            $tmpOrderInfo = Order::withTrashed()->where(['id' => $tmpOrderId])->first()->toArray();


            //产品数量处理
            $productNum = '';
            if ($tmpOrderInfo['product_num']) {
                $tmpProductNumArr = explode(',', $tmpOrderInfo['product_num']);
                if (isset($tmpProductNumArr[0])) {
                    $productNum = $tmpProductNumArr[0];
                }
            }


            $productName = \App\Engine\OrderEngine::getOrderFiledValueTrue($tmpOrderInfo['product_name'], 20);
            $tmpArr[] = [
                'order_plate_id' => $orderPlateRow['id'],//工单id
                'order_id' => $tmpOrderInfo['id'],//工单id
                'order_title' => $tmpOrderInfo['order_title'],//工单号
//                'product_num' => $productNum,//产品数量
                'product_num' => isset($orderPlateRow['number']) ? $orderPlateRow['number'] : '',//产品数量
                'product_name' => $productName,//产品名称
                'create_date' => date('Y-m-d', $tmpOrderInfo['created_at']),//创建时间
            ];
        }
        $orderPlateList = $tmpArr;

        return [
            'allCount' => $allCount,
            'orderPlateList' => $orderPlateList,
        ];

    }

    /**
     * Description:获取工单列表
     * User: zhuyujun
     */
    public function getOrderList()
    {

        $userId = Func::getHeaderValueByName('userid');

        //判断用户是否为管理员
        $userInfo = DepartmentUser::getCurrentInfo($userId)->toArray();
        $companyId = isset($userInfo['company_id']) ? $userInfo['company_id'] : '';

        $isDistribute = request('is_distribute');//是否派发 1-已派发 0-未派发
        $isManager = Privilege::getAppnodeId($userInfo['privilege_id'], 1);//是否为下单人（管理员权限）
        $isSupremeAuthority = Privilege::getAppnodeId($userInfo['privilege_id'], 9);//是否为厂长（最高权限）

        //工单筛选
        $orderStauts = request('order_status');//筛选的工单状态，1-待开工 2-进行中 3-已完成
        $orderTitle = request('order_title');//筛选的工单号


        $customerId = request('customer_id');//筛选的工单号
        if ($customerId) {
            $orderList = OrderListRelation::where(['type' => 1, 'customer_id' => $customerId])->orderBy('order_create_time', 'desc')->get()->toArray();
            return $this->distributeData($orderList);
        }


        if ($isDistribute) {//已派发
            ////新方法实现工单列表
            //处理工单状态搜索
            if (!$orderStauts) {
                if ($isSupremeAuthority) {
                    $where = [['company_id', '=', $companyId]];
                } else {
                    $where = [['uid', '=', $userId], ['company_id', '=', $companyId]];
                }


                //下单人不展示工序订单
                if ($isManager || $isSupremeAuthority) {
                    $where[] = ['type', '!=', 2];
                }

                if ($orderTitle) {
                    $where[] = ['content', 'like', '%' . $orderTitle . '%'];
                }
                $orderList = OrderListRelation::where($where)->orderBy('order_create_time', 'desc')->get()->toArray();
            } else {
                if ($orderStauts == 1) {//待接单
                    //主订单
                    if ($isSupremeAuthority) {
                        $where = [['company_id', '=', $companyId], ['status', '=', 1], ['type', '=', 1]];
                    } else {
                        $where = [['uid', '=', $userId], ['company_id', '=', $companyId], ['status', '=', 1], ['type', '=', 1]];
                    }


                    //下单人不展示工序订单
                    if ($isManager || $isSupremeAuthority) {
                        $where[] = ['type', '!=', 2];
                    }

                    if ($orderTitle) {
                        $where[] = ['order_title', 'like', '%' . $orderTitle . '%'];
                    }
                    $orderList1 = OrderListRelation::where($where)->orderBy('order_create_time', 'desc')->get()->toArray();

                    //工序订单
                    $where = [['uid', '=', $userId], ['company_id', '=', $companyId]];
                    if ($orderTitle) {
                        $where[] = ['order_title', 'like', '%' . $orderTitle . '%'];
                    }
                    $whereTypeIn = [2, 3];
                    $whereStatusIn = [1, 2, 101];
                    $orderList2 = OrderListRelation::where($where)->whereIn('type', $whereTypeIn)->whereIn('status', $whereStatusIn)->orderBy('order_create_time', 'desc')->get()->toArray();


                    //员工订单
                    $where = [['uid', '=', $userId], ['company_id', '=', $companyId], ['type', '=', 4]];
                    if ($orderTitle) {
                        $where[] = ['order_title', 'like', '%' . $orderTitle . '%'];
                    }
                    $whereStatusIn = [1, 2, 101];
                    $orderList3 = OrderListRelation::where($where)->whereIn('status', $whereStatusIn)->orderBy('order_create_time', 'desc')->get()->toArray();

                    $orderList = array_merge($orderList1, $orderList2, $orderList3);
                } elseif ($orderStauts == 2) {//进行中
                    //主订单
                    if ($isSupremeAuthority) {
                        $where = [['company_id', '=', $companyId], ['type', '=', 1], ['status', '=', 2]];
                    } else {
                        $where = [['uid', '=', $userId], ['company_id', '=', $companyId], ['type', '=', 1], ['status', '=', 2]];
                    }

                    if ($orderTitle) {
                        $where[] = ['order_title', 'like', '%' . $orderTitle . '%'];
                    }
                    $orderList1 = OrderListRelation::where($where)->orderBy('order_create_time', 'desc')->get()->toArray();

                    //工序订单
                    $where = [['uid', '=', $userId], ['company_id', '=', $companyId], ['type', '!=', 1], ['type', '!=', 4], ['status', '=', 3]];

                    //下单人不展示工序订单
                    if ($isManager || $isSupremeAuthority) {
                        $where[] = ['type', '!=', 2];
                    }

                    if ($orderTitle) {
                        $where[] = ['order_title', 'like', '%' . $orderTitle . '%'];
                    }
                    $orderList2 = OrderListRelation::where($where)->orderBy('order_create_time', 'desc')->get()->toArray();

                    //员工订单
                    $where = [['uid', '=', $userId], ['company_id', '=', $companyId], ['type', '=', 4], ['status', '=', 3]];
                    if ($orderTitle) {
                        $where[] = ['order_title', 'like', '%' . $orderTitle . '%'];
                    }
                    $orderList3 = OrderListRelation::where($where)->orderBy('order_create_time', 'desc')->get()->toArray();
                    $orderList = array_merge($orderList1, $orderList2, $orderList3);

                } elseif ($orderStauts == 3) {//已完成
                    if ($isSupremeAuthority) {
                        $where = [['uid', '=', $userId], ['company_id', '=', $companyId], ['type', '=', 1], ['status', '=', 3]];
                        $orWhere = [['uid', '=', $userId], ['company_id', '=', $companyId], ['type', '!=', 1], ['status', '=', 4]];
                    } else {
                        $where = [['uid', '=', $userId], ['company_id', '=', $companyId], ['type', '=', 1], ['status', '=', 3]];
                        $orWhere = [['uid', '=', $userId], ['company_id', '=', $companyId], ['type', '!=', 1], ['status', '=', 4]];
                    }

                    //下单人不展示工序订单
                    if ($isManager || $isSupremeAuthority) {
                        $orWhere[] = ['type', '!=', 2];
                    }

                    if ($orderTitle) {
                        $where[] = ['order_title', 'like', '%' . $orderTitle . '%'];
                        $orWhere[] = ['order_title', 'like', '%' . $orderTitle . '%'];
                    }
                    $orderList = OrderListRelation::where($where)->orWhere($orWhere)->orderBy('order_create_time', 'desc')->get()->toArray();
                }
            }

            return $this->distributeData($orderList);
        } else {//未派发工单
            if ($isSupremeAuthority) {
                $orderList = Order::where('status', 4)->orderBy('id', 'desc')->get()->toArray();
            } else {
                $orderList = Order::where('status', 4)->where(['uid' => $userId])->orderBy('id', 'desc')->get()->toArray();
            }


            foreach ($orderList as $k => $v) {
                $orderList[$k]['created_at'] = date('Y年m月d日', $v['created_at']);
                $orderList[$k]['updated_at'] = date('Y年m月d日', $v['updated_at']);
            }

            return $orderList;
        }

    }


    //未派发列表(新)
    public function getNoAssignOrderList()
    {
        $userId = Func::getHeaderValueByName('userid');

        //判断用户是否为管理员
        $userInfo = DepartmentUser::getCurrentInfo($userId)->toArray();
        $companyId = isset($userInfo['company_id']) ? $userInfo['company_id'] : '';

        $isDistribute = request('is_distribute');//是否派发 1-已派发 0-未派发
        $isManager = Privilege::getAppnodeId($userInfo['privilege_id'], 1);//是否为下单人（管理员权限）
        $isSupremeAuthority = Privilege::getAppnodeId($userInfo['privilege_id'], 9);//是否为厂长（最高权限）

        if ($isSupremeAuthority) {
            $orderList = Order::where('status', 4)->where(['company_id' => $companyId])->orderBy('id', 'desc')->get()->toArray();
        } else {
            $orderList = Order::where('status', 4)->where(['company_id' => $companyId, 'uid' => $userId])->orderBy('id', 'desc')->get()->toArray();
        }


        $newOrderList = [];
        foreach ($orderList as $k => $tmpOrderRow) {
            //获取生产实例图
            $productionCaseDiagramIds = isset($tmpOrderRow['production_case_diagram']) ? $tmpOrderRow['production_case_diagram'] : '';
            if ($productionCaseDiagramIds) {
                $tmpArr = explode(',', $productionCaseDiagramIds);
                $productionCaseDiagramId = reset($tmpArr);
                $productionCaseDiagram = ImgUpload::getImgUrlById($productionCaseDiagramId);
                if (!$productionCaseDiagram) {//未获取到id对应的图片
                    $productionCaseDiagram = env('APP_URL') . '/assets/mobile/common/images/order_list_default.png';
                }

            } else {
                $productionCaseDiagram = env('APP_URL') . '/assets/mobile/common/images/order_list_default.png';
            }


            $tmpOrderRow = \App\Engine\OrderEngine::dealOrderFiled($tmpOrderRow);


            //订单创建时间（派发时间）
            $orderCreateTime = $tmpOrderRow['created_at'];
            if ($orderCreateTime) {
                $orderCreateTime = date('Y-m-d', $orderCreateTime);
            }

            //获取工序类型名称
            $orderTypeTitle = OrderType::getOneValueById($tmpOrderRow['order_type'], 'title');

            $imgId = $tmpOrderRow['production_case_diagram'];


            $productName = \App\Engine\OrderEngine::getOrderFiledValueTrue($tmpOrderRow['product_name'], 20);

            $tmpOrderRow['order_title'] = \App\Engine\Common::changeSnCode($tmpOrderRow['order_title']);
            $tmpDataRow = [
                'customer_title' => '单位名称',//工单列表展示字段
                'product_title' => '品名',//工单列表展示字段
                'order_title' => '单号',//工单列表展示字段
                'customer_name' => isset($tmpOrderRow['field_name_23']) ? $tmpOrderRow['field_name_23'] : '',//新加字段客户
                'product_name' => isset($productName) ? $productName : '',//新加字段品名
                'order_title_value' => $tmpOrderRow['order_title'],//新加字段单号
                'firstPropertyName' => '成品规格',
                'secondPropertyName' => '数量',
                'thirdPropertyName' => '交货日期',
                'thirdPropertyValue' => $tmpOrderRow['finished_date'],
                'secondPropertyValue' => $tmpOrderRow['product_num'],
                'firstPropertyValue' => isset($tmpOrderRow['finished_specification']) ? $tmpOrderRow['finished_specification'] : '',
                'productionCaseDiagram' => $productionCaseDiagram,
                'productOrderTimeValue' => $orderCreateTime,
                'orderTypeTitle' => $orderTypeTitle,
                'orderNumberValue' => $orderTypeTitle,
                'orderTimeValue' => $tmpOrderRow['finished_date'],
                'relate_id' => $tmpOrderRow['id'],
                'orderStatus' => '待派发',
                'order_type' => $tmpOrderRow['order_type'],
                'img_id' => $imgId,
            ];

            $newOrderList[] = $tmpDataRow;
        }

        return $newOrderList;
    }


    //获取工单详情
    public function getOrderDetail(Request $request)
    {
        //获取传入数据
        $input = $request->all();
        $input['order_process_id'] = isset($input['order_process_id']) ? $input['order_process_id'] : '';
        $input['order_process_course_id'] = isset($input['order_process_course_id']) ? $input['order_process_course_id'] : '';//员工工单id
        $inputType = isset($input['type']) ? $input['type'] : 0;
        $inputUserId = isset($input['user_id']) ? $input['user_id'] : 0;


        $userId = Func::getHeaderValueByName('userid');

        //逻辑调整传入的id实际为员工工单id
        if ($input['order_process_course_id']) {
            $orderProcessCourseId = $input['order_process_course_id'];
            $orderProcessCourseRow = OrderProcessCourse::where(['id' => $orderProcessCourseId])->first()->toArray();
            $input['order_process_id'] = $orderProcessCourseRow['order_process_id'];
            $userId = $orderProcessCourseRow['uid'];
        }

//        if($inputType==1 && $inputUserId>0)
//        {
//            $userId = $inputUserId;
//        }
        $userInfo = DepartmentUser::getCurrentInfo($userId)->toArray();
        $companyId = $userInfo['company_id'];

        //校验参数
        $rules = [
            'order_process_id' => 'required',
        ];
        $messages = [
            'order_process_id.required' => '缺少工单id',
        ];
        $this->validateRequestParameters($input, $rules, true, $messages);

        //获取对应工序信息
        $orderProcessInfo = OrderProcess::where('id', $input['order_process_id'])->first()->toArray();
        //获取工单信息
        $orderInfo = Order::where('id', $orderProcessInfo['order_id'])->first()->toArray();
        //获取工序名称
        $processTitle = Process::getOneValueById($orderProcessInfo['process_type'], 'title');

        //获取工序类型名称
        $orderTypeTitle = OrderType::getOneValueById($orderInfo['order_type'], 'title');

        $processFieldList = Process::getFieldListByProcessId($orderProcessInfo['process_type']);

        //获取用户的权限
        $userRights = PermissionEngine::getUserStepPrivilegeByProcess($userId, $orderProcessInfo['process_type'], $orderInfo['order_type'])->toArray();

        $apeList = [];

        //追加工单基础信息
        $processOrderTypeId = $orderProcessInfo['ordertype_process_id'];//工序工单
        $privilegeId = $userInfo['privilege_id'];//角色id
        $baseFieldList = PermissionEngine::getBasePrivilegeFieldsByProcessOrderType($processOrderTypeId, $privilegeId);

        foreach ($baseFieldList as $baseFieldRow) {
            if (isset($orderInfo[$baseFieldRow['field_name']])) {
                $showTitle = $orderInfo[$baseFieldRow['field_name']];//默认展示字段的内容
            }

            $tmpFiledType = \App\Eloquent\Ygt\OrderFieldCompany::getFieldTypeByFieldName($baseFieldRow['field_name'], $companyId);
            $showTitle = $orderInfo[$baseFieldRow['field_name']];//默认展示字段的内容

            $showTitle = OrderEngine::getOrderFiledValueTrue($orderInfo[$baseFieldRow['field_name']], $tmpFiledType);


            $apeList[] = [
                '$leftLabelValue' => $baseFieldRow['title'],
                '$rightLabelValue' => $showTitle,
            ];
        }


        foreach ($processFieldList as $processFieldRow) {
            if ($processFieldRow['field_name'] == 'remark') {//备注另外处理
                continue;
            }

            //通过字段类型不同处理
            //获取字段对应的类型1=>'文本',2=>'文本域',3=>'下拉框-跳界面',4=>'跳材料',5=>'有单位',6=>'开关',7=>'时间'
            $tmpFiledType = ProcessField::getFieldTypeByFieldName($processFieldRow['field_name'], $companyId);
            $showTitle = $orderProcessInfo[$processFieldRow['field_name']];//默认展示字段的内容

            $showTitle = OrderEngine::getOrderFiledValueTrue($orderProcessInfo[$processFieldRow['field_name']], $tmpFiledType);

            //员工订单详情-工单的需完成数量改为员工被派发的数量
            if ($input['order_process_course_id']) {//用户为员工
                if ($processFieldRow['field_name'] == 'completed_number') {//需完成数量，员工使用被分配的数量
                    $showTitle = $orderProcessCourseRow['total_number'];
                }
            }


            //版跳转问题
            $plateId = 0;
            if ($tmpFiledType == 17 && $orderProcessInfo[$processFieldRow['field_name']]) {
                $tmpCreateOrderPlateId = $orderProcessInfo[$processFieldRow['field_name']];
                $tmpCreateOrderPlateRow = \App\Eloquent\Ygt\CreateOrderPlate::where(['id'=>$tmpCreateOrderPlateId])->first();
                $tmpCreateOrderPlateRowContent =json_decode(htmlspecialchars_decode($tmpCreateOrderPlateRow['content']), true);
                //显示固定版、套版组合
                if(isset($tmpCreateOrderPlateRowContent['branch']['fixed_plate'])){
                    $tmpReList = \App\Engine\OrderEngine::getOrderPlateDealInfo($tmpCreateOrderPlateRowContent,$processFieldRow['title']);
                    foreach ($tmpReList as $tmpReRow){
                        $apeList[] = $tmpReRow;
                    }
                }
            }elseif($tmpFiledType == 22 && $orderProcessInfo[$processFieldRow['field_name']]){
                $tmpCreateOrderProcessProductId = $orderProcessInfo[$processFieldRow['field_name']];
                $tmpCreateOrderProcessProductRow = \App\Eloquent\Ygt\CreateOrderProcessProduct::where(['id'=>$tmpCreateOrderProcessProductId])->first();
                $tmpCreateOrderProcessProductRowContent =json_decode(htmlspecialchars_decode($tmpCreateOrderProcessProductRow['content']), true);
                if($tmpCreateOrderProcessProductRowContent){
                    ///显示半成品信息
                    foreach ($tmpCreateOrderProcessProductRowContent as $tmpCreateOrderProcessProductRowContentRow){
                        $apeList[] = [
                            '$leftLabelValue' => $processFieldRow['title'],
                            '$rightLabelValue' => "【{$tmpCreateOrderProcessProductRowContentRow['number']}】{$tmpCreateOrderProcessProductRowContentRow['process_product_title']}",
                        ];
                    }
                }
            }
            else{
                $apeList[] = [
                    '$leftLabelValue' => $processFieldRow['title'],
                    '$rightLabelValue' => $showTitle,
                    '$plateId' => $plateId,
                ];
            }
        }


        //追加需完成数量
        $orderProcessNeedNum = \App\Engine\OrderEngine::getOrderPorcessNeedNum($orderProcessInfo['process_type'],$orderInfo);
        if ($orderProcessNeedNum) {

            //获取工艺单位
            $curProcessRow = \App\Eloquent\Ygt\Process::getInfo(['id' => $orderProcessInfo['process_type']])->toArray();
            if($curProcessRow['measurement_unit']){
                $curProcessMeasurementUnit = $curProcessRow['measurement_unit'];
            }else{
                $curProcessMeasurementUnit = '';
            }

            $apeList[] = [
                '$leftLabelValue' => '需完成数量',
                '$rightLabelValue' => $orderProcessNeedNum.$curProcessMeasurementUnit,
            ];
        }


        //添加计件工资
        $orderProcessId = $orderProcessInfo['id'];
        if (isset($orderProcessId, $privilegeId, $orderProcessCourseId)) {
            $pieceWage = \App\Engine\OrderEngine::getEmployeePieceWage($orderProcessId, $privilegeId, $orderProcessCourseId);
            $apeList[] = [
                '$leftLabelValue' => '计件工资',
                '$rightLabelValue' => $pieceWage ? $pieceWage : '未设置',
            ];
        }

        //处理图片数据
        $imgIdList = explode(',', $orderInfo['production_case_diagram']);
        $exampleImg = '';
        foreach ($imgIdList as $imgId) {
            if (!trim($imgId)) {//过滤空格 图片id应该不会有0
                continue;
            }
            if (!$exampleImg) {//取第一张图作为示例图
                $exampleImg = ImgUpload::getImgUrlById($imgId);
            }
        }

        //获取上一个部门&上一个部门
        $preProcessList = OrderType::getAllPrevOrderProcess($orderInfo['order_type'], $orderProcessInfo['process_type']);
        if ($preProcessList) {
            $preProcessList = $preProcessList->toArray();
        } else {
            $preProcessList = [];
        }


        //获取工序数量是否需要叠加&工序名称
        $processId = $orderProcessInfo['process_type'];
        $where = ['id' => $processId];
        $process = Process::getInfo($where)->toArray();

        //获取预估完成时间最晚的一个，待开工的部门优先级最高
        $preProcess = '';//上一个工序（部门）
        $preProcessEstimatedTime = 0;
        $preProcessEstimatedTimeStr = '';
        $lastOrderProcessId = 0;
        $finishNum = 0;
        $preProcessMeasurementUnit = '';
        $isPreEmpty = 0;

        if ($preProcessList) {
            foreach ($preProcessList as $processId) {
                //获取工序信息
                $preOrderProcessInfo = OrderProcess::where(['order_id' => $orderInfo['id'], 'process_type' => $processId])->first()->toArray();


//                $preProcess = Process::getOneValueById($preOrderProcessInfo['process_type'], 'title');
//                $processIsSum = Process::getOneValueById($preOrderProcessInfo['process_type'], 'is_sum');

                //获取工序数量是否需要叠加&工序名称
                $where = ['id' => $processId];
                $process = Process::getInfo($where)->toArray();
                $preProcess = $process['title'];//工序名称
                $processIsSum = $process['is_sum'];//工序数量是否累加 0-不累加 1-累加




                $lastOrderProcessId = $preOrderProcessInfo['id'];
                if ($preOrderProcessInfo['status'] == 1) {//待开工
                    $preProcessEstimatedTimeStr = '待开工';
                    break;
                } else {

                    //调整-预计完成时间调整为从员工工单获取
                    $orderProcessCourseList = OrderProcessCourse::where(['order_process_id' => $preOrderProcessInfo['id']])->get();
                    $finishNum = 0;
                    $finishUserNumList = [];
                    foreach ($orderProcessCourseList as $orderProcessCourseRow) {

                        $tmpPreProcessEstimatedTime = $orderProcessCourseRow['start_time'] + $orderProcessCourseRow['estimated_time_hour'] * 3600 + $orderProcessCourseRow['estimated_time_minute'] * 60;
                        if ($tmpPreProcessEstimatedTime > $preProcessEstimatedTime) {
                            $preProcessEstimatedTime = $tmpPreProcessEstimatedTime;
                            $preProcessEstimatedTimeStr = '预计完成时间:' . date('Y年m月d日 H时', $preProcessEstimatedTime);
                        }


                        //设定的角色不进行统计数量到工序数量中
                        //过滤异常数据
                        if (!DepartmentUser::getCurrentInfo($orderProcessCourseRow['uid'])) {
                            continue;
                        }
                        $tmpUserInfo = DepartmentUser::getCurrentInfo($orderProcessCourseRow['uid'])->toArray();
                        $tmpPrivilegeId = $tmpUserInfo['privilege_id'];
                        if (OrderEngine::getProcessNumNoStatistics($tmpPrivilegeId)) {
                            continue;
                        }


                        $finishNum += $orderProcessCourseRow['finish_number'];
                        if (!$processIsSum) {//不累加
                            $tmpUserInfo = DepartmentUser::getCurrentInfo($orderProcessCourseRow['uid'])->toArray();
                            $tmpPrivilegeId = $tmpUserInfo['privilege_id'];
                            if (isset($finishUserNumList[$tmpPrivilegeId])) {
                                $finishUserNumList[$tmpPrivilegeId]['finish_number'] += $orderProcessCourseRow['finish_number'];
                            } else {
                                $finishUserNumList[$tmpPrivilegeId]['finish_number'] = $orderProcessCourseRow['finish_number'];
                            }
                        }


                    }


                    if ($preProcessEstimatedTime < 631152000) {//过滤1970的情况
                        $preProcessEstimatedTimeStr = '';
                    }

                    //不累加--未完工时取完成量最小的员工
                    if (!empty($finishUserNumList)) {
                        $finishMinNum = '';
                        foreach ($finishUserNumList as $finishUserNumRow) {
                            if ($finishMinNum === 0) {//如果有员工完成数量为0，
                                break;
                            }

                            if ($finishUserNumRow['finish_number'] < $finishMinNum || $finishMinNum === '') {//如果有员工完成数量更少，或者第一个员工的数据
                                $finishMinNum = $finishUserNumRow['finish_number'];
                            }
                        }
                        $finishNum = $finishMinNum;
                        $preProcessMeasurementUnit = $process['measurement_unit'];
                    }


                    if ($preOrderProcessInfo['status'] == 4) {//追加该部门完成数量
//                        $preProcessEstimatedTimeStr .= " 完成数量:" . $finishNum;
                    }
                }
            }
        } else {
            $preProcess = '无';//上一个工序（部门）
            $preProcessEstimatedTimeStr = '';
            $isPreEmpty = 1;
        }


        //返回数据权限
        $isManager = Privilege::getAppnodeId($userInfo['privilege_id'], 1);//是否为下单人（管理员权限）
        if (in_array(3, $userRights) || $isManager) {//有分配权限或者是管理员权限
            if ($orderProcessInfo['status'] == 1) {
                $sureButtonFunctionName = 'orderSureAction';
                $buttonTitleValue = '确认接单';
            } elseif ($orderProcessInfo['status'] == 2) {
                $sureButtonFunctionName = 'allotOrderAction';
                $buttonTitleValue = '派发工单';
            }

            $returnOrderInfo = [];
            $returnOrderInfo['pageID'] = 3;

//            $returnOrderInfo['completed_number'] = $orderProcessInfo['completed_number'];
            $orderProcessNeedNum = \App\Engine\OrderEngine::getOrderPorcessNeedNum($orderProcessInfo['process_type'],$orderInfo);
            $returnOrderInfo['completed_number'] = $orderProcessNeedNum;

            $orderInfo['order_title'] = \App\Engine\Common::changeSnCode($orderInfo['order_title']);
            $returnOrderInfo['data'] = [
                '$productNameValue' => $orderTypeTitle,
                '$productOrderValue' => '生产单号:' . $orderInfo['order_title'],
                '$productTimeValue' => '交货日期:' . $orderInfo['finished_date'],
                '$futureTimeValue' => $preProcessEstimatedTimeStr,
                '$prevDepartmentValue' => $preProcess,
                'is_pre_empty' => $isPreEmpty,//1-没有上一工序 0-有
                '$last_order_process_finish_num' => $finishNum.$preProcessMeasurementUnit,//上一部门完成数量
                '$lastOrderProcessId' => $lastOrderProcessId,
                '$titleLabelValue' => $processTitle,
                '$commentValue' => $orderProcessInfo['remark'],
                '$buttonTitleValue' => $buttonTitleValue,
                '$sureButtonFunctionName' => $sureButtonFunctionName . $orderProcessInfo['id'],
                '$imageClick' => 'imageClickAction' . $orderInfo['id'],
                '$productImagrUlr' => $exampleImg,
                '$list' => $apeList,
            ];
        } else {

            //判断员工能否开工
            $orderProcessId = $orderProcessInfo['id'];
            //获取前一步骤所有工艺
            $preOrderProcessList = OrderType::getAllPrevOrderProcess($orderInfo['order_type'], $orderProcessInfo['process_type']);
            if ($preOrderProcessList) {
                $preOrderProcessList = $preOrderProcessList->toArray();
            } else {
                $preOrderProcessList = [];
            }


            $returnOrderInfo = [];
            $returnOrderInfo['pageID'] = 3;

            $orderInfo['order_title'] = \App\Engine\Common::changeSnCode($orderInfo['order_title']);
            $returnOrderInfo['data'] = [
                '$productNameValue' => $orderTypeTitle,
                '$productOrderValue' => '生产单号:' . $orderInfo['order_title'],
                '$productTimeValue' => '交货日期:' . $orderInfo['finished_date'],
                '$futureTimeValue' => $preProcessEstimatedTimeStr,
                '$prevDepartmentValue' => $preProcess,
                'is_pre_empty' => $isPreEmpty,//1-没有上一工序 0-有
                '$last_order_process_finish_num' => $finishNum.$preProcessMeasurementUnit,//上一部门完成数量
                '$lastOrderProcessId' => $lastOrderProcessId,
                '$titleLabelValue' => $processTitle,
                '$list' => $apeList,
                '$commentValue' => $orderProcessInfo['remark'],
                '$buttonTitleValue' => '确认开工',
                '$sureButtonFunctionName' => 'sureGoAction' . $orderProcessCourseId,
                '$imageClick' => 'imageClickAction' . $orderInfo['id'],
                '$productImagrUlr' => $exampleImg
            ];

        }
//        if($inputType==1)
//        {
//            $returnOrderInfo['data']['$buttonTitleValue']='车间版开工';
//        }
        return $returnOrderInfo;
    }

    //确认开工
    public function confirmStart(Request $request)
    {
        //获取传入数据
        $input = $request->all();
        $input['order_process_id'] = isset($input['order_process_id']) ? $input['order_process_id'] : '';
        $input['order_process_course_id'] = isset($input['order_process_course_id']) ? $input['order_process_course_id'] : '';
        $input['estimated_time_hour'] = isset($input['estimated_time_hour']) ? $input['estimated_time_hour'] : '';//预估时间
        $input['estimated_time_minute'] = isset($input['estimated_time_minute']) ? $input['estimated_time_minute'] : '';//预估时间

        //处理时间，通过预计完成时间，推算出耗时多少小时多少分
        $curTime = time();
        $postEstimatedTime = $input['estimated_time_hour'];//记录预计完成时间
        if ($input['estimated_time_hour']) {
            //计算到指定时间需要的秒数
            $needTime = strtotime($input['estimated_time_hour']) - time();
            $input['estimated_time_minute'] = $needTime / 60;
            $input['estimated_time_hour'] = 0;
        }

        $userId = Func::getHeaderValueByName('userid');

        //逻辑调整传入的id实际为员工工单id
        if ($input['order_process_course_id']) {
            $orderProcessCourseId = $input['order_process_course_id'];
            $orderProcessCourseRow = OrderProcessCourse::where(['id' => $orderProcessCourseId])->first()->toArray();
            $orderProcessId = $orderProcessCourseRow['order_process_id'];
            $input['order_process_id'] = $orderProcessCourseId;
            $userId = $orderProcessCourseRow['uid'];
        } else {
            $orderProcessId = $input['order_process_id'];
        }

        //校验参数
        $rules = [
            'order_process_id' => 'required',
        ];
        $messages = [
            'order_process_id.required' => '缺少工单id',
        ];
        $this->validateRequestParameters($input, $rules, true, $messages);

        //如果前一步骤的工序未全部完工不允许开工
        //获取对应工单工序表信息
        $orderProcessInfo = OrderProcess::where('id', $orderProcessId)->first()->toArray();
        //获取工单信息
        $orderInfo = Order::where('id', $orderProcessInfo['order_id'])->first()->toArray();
        $orderId = $orderInfo['id'];
        $foreignKey = intval($orderInfo['customer_order_id']);
        $order_title = $orderInfo['order_title'];

        $userRights = PermissionEngine::getUserStepPrivilegeByProcess($userId, $orderProcessInfo['process_type'], $orderInfo['order_type'])->toArray();
        if (in_array(3, $userRights)) {//有分配权限 1:查看;2:可写;3:分配;4:提交;5:转发;
            //判断是否发信息给下一道工艺的员工

            //添加预估时间&修改工单工序状态&修改主工单状态
            //获取对应工序信息
            $orderProcessObj = OrderProcess::where('id', $input['order_process_id'])->first();

            //        $orderProcessObj->estimated_time = $input['estimated_time'];
            $orderProcessObj->estimated_time_hour = $input['estimated_time_hour'];
            $orderProcessObj->estimated_time_minute = $input['estimated_time_minute'];
            $orderProcessObj->start_time = $curTime;
            $orderProcessObj->status = 2;
            $orderProcessObj->uid = $userId;
            $orderProcessObj->save();


            //更新管理员消息状态为1需分配(需原状态为1需接单)
            $typeUserId = $orderProcessObj->uid;
            $typeId = $orderProcessObj->id;
            UserMessage::updateTypeStatusByTypeId(2, $typeId, $typeUserId, 2);

            //修改工单列表关联表数据状态
            $type = 2;//工序工单
            $relateId = $orderProcessObj->id;
            $status = 2;
            OrderEngine::changeOrderListRelationStatus($type, $relateId, $status);

            //工序管理员确认接单后，修改主工单状态
            $orderObj = Order::where('id', $orderId)->first();
            if ($orderObj->status == 1) {
                $orderObj->status = 101;
                $orderObj->save();

                //修改工单列表关联表数据状态
                $type = 1;
                $relateId = $orderObj->id;
                $status = 101;
                OrderEngine::changeOrderListRelationStatus($type, $relateId, $status);
            }

        } else {//普通员工提交
            //获取前一步骤所有工艺
            $preOrderProcessList = OrderType::getAllPrevOrderProcess($orderInfo['order_type'], $orderProcessInfo['process_type'])->toArray();
            //获取订单类型是否允许同时开工
            $orderTypeProcessId = OrderProcess::where('id', $orderProcessId)->first()->ordertype_process_id;
            $isMeanwhile = OrderType::isMeanwhileNextStep($orderTypeProcessId);

            if ($isMeanwhile) {
                //如果前面的工序已经开工则允许开工
                //前面的步骤待开工的数量（状态 1：待接单 2：待分派）
                $noStartProcessNum = OrderProcess::all()->whereIn('process_type', $preOrderProcessList)->whereIn('status', array(1, 2, 101))->where('order_id', $orderProcessInfo['order_id'])->count();
                if ($noStartProcessNum != 0) {
                    return [
                        'code' => 1,
                        'message' => '请等待上道工序开工'
                    ];
                }
            } else {
                //判断对应步骤的工艺是否都已经完成
                $noCompleteProcessNum = OrderProcess::all()->whereIn('process_type', $preOrderProcessList)->where('status', '!=', 4)->where('order_id', $orderProcessInfo['order_id'])->count();
                if ($noCompleteProcessNum != 0) {
                    return [
                        'code' => 1,
                        'message' => '请等待上道工序完工'
                    ];
                }
            }


            $orderProcessCourseObj = OrderProcessCourse::where('id', $input['order_process_id'])->first();
            //限制多次开工
            if ($orderProcessCourseObj->status != 1 && $orderProcessCourseObj->status != 2) {
                return [
                    'code' => 1,
                    'message' => '工单已经开工，请刷新页面'
                ];
            }

            //        $orderProcessCourseObj->estimated_time = $input['estimated_time'];
            //$overUserRow = DepartmentUser::getInfo(['user_id' => $orderProcessInfo['uid']])->toArray();

            $processTitle = Process::getOneValueById($orderProcessInfo['process_type'], 'title');

            //更新员工消息状态为2已接单(需原状态为1需接单)
            $courseUserId = $orderProcessCourseObj->uid;
            $courseId = $orderProcessCourseObj->id;
            UserMessage::updateTypeStatusByTypeId(1, $courseId, $courseUserId, 3);
            $courseUser = DepartmentUser::getCurrentInfo($courseUserId)->toArray();

            //员工给对应的管理员发一条开工消息
            //$typeUserId = $orderProcessInfo['uid'];
            $typeUserId = $orderProcessCourseObj->assign_id;
            $orderInfoProductNum = $orderInfo['product_num'];
            $orderInfoProductNum = str_replace(',', '', $orderInfoProductNum);
            $orderInfoSpecification = $orderInfo['finished_specification'];
            if ($orderInfoSpecification) {
                $orderInfoSpecification = str_replace(',', '×', $orderInfoSpecification);
                $orderInfoSpecification .= '厘米';
            }
            $fieldName23 = $this->changeFieldName23($orderInfo['field_name_23']);
            $productName = \App\Engine\OrderEngine::getOrderFiledValueTrue($orderInfo['product_name'], 20);

//            $messageContent = $processTitle . 'rnrn';
//            $messageContent .= "单位名称：{$fieldName23}rnrn品名：{$productName}rnrn";
//            $messageContent .= "成品规格：{$orderInfoSpecification}rnrn数量：{$orderInfoProductNum}rnrn";
//            $messageContent .= "交货日期：{$orderInfo['finished_date']}";

//            主题：工单已开工
//内容：工单号、单位名称、品名，预计完工时间
            $tmpOrderTitle = \App\Engine\Common::changeSnCode($orderInfo['order_title']);
            $messageContent = "工单号：{$tmpOrderTitle}rnrn";
            $messageContent .= "单位名称：{$fieldName23}rnrn";
            $messageContent .= "品名：{$productName}rnrn";
            $messageContent .= "预计完工时间：{$postEstimatedTime}rnrn";

            $data = [
                'company_id' => $orderProcessInfo['company_id'],
                'privilege_id' => '',
                'form_user_id' => $userId,
                'to_user_id' => $typeUserId,
                'foreign_key' => $foreignKey,
                'type' => 3,
                'type_id' => $courseId,
                'title' => $order_title,
                'content' => $messageContent,
                'theme' => '工单已开工',
            ];
            UserMessage::sendCustomerOrderMessage($data);

            //给下一工序的工序管理员和员工（如果已派发）发送消息
            //获取上一个部门&上一个部门
            $processOrderTypeObj = ProcessOrdertype::where(['id' => $orderProcessInfo['ordertype_process_id']])->first();
            $stepNumber = false;
            if ($processOrderTypeObj) {
                $stepNumber = $processOrderTypeObj->step_number;
            }

            $nextProcessList = OrderType::getAllNextOrderTypeProcess($orderInfo['order_type'], $orderProcessInfo['process_type'], $stepNumber);
            foreach ($nextProcessList as $nextOrderTypeProcessId) {
                //给工序管理员发送消息
                $tmpNextOrderProcessRow = OrderProcess::where(['order_id' => $orderId, 'ordertype_process_id' => $nextOrderTypeProcessId])->first()->toArray();
                $tmpNextOrderProcessId = $tmpNextOrderProcessRow['id'];
                $tmpNextOrderProcessUid = $tmpNextOrderProcessRow['uid'];

                //工单号、彩印员工（机台号）、预计完工时间

//                $messageContent = "上一道工序【{$processTitle}】rnrn开工了";

                $userInfo = \App\Eloquent\Ygt\DepartmentUser::getCurrentInfo($userId)->toArray();
                $messageContent = "工单号：{$tmpOrderTitle}rnrn";
                $messageContent .= "员工：{$userInfo['truename']}rnrn";
                $messageContent .= "预计完工时间：{$postEstimatedTime}rnrn";

                $data = [
                    'company_id' => $orderProcessInfo['company_id'],
                    'privilege_id' => '',
                    'form_user_id' => $userId,
                    'to_user_id' => $tmpNextOrderProcessUid,
                    'foreign_key' => $foreignKey,
                    'type' => 9,
                    'type_id' => $orderProcessInfo['id'],
                    'title' => $tmpOrderTitle,
                    'content' => $messageContent,
                    'theme' => "{$tmpOrderTitle}已开工",
                ];
                UserMessage::sendCustomerOrderMessage($data);


                //给已经分派了员工工单的员工发送消息
                $tmpNextOrderProcessCourseList = OrderProcessCourse::where(['order_process_id' => $tmpNextOrderProcessId])->get();
                foreach ($tmpNextOrderProcessCourseList as $tmpNextOrderProcessCourseRow) {
                    $data = [
                        'company_id' => $orderProcessInfo['company_id'],
                        'privilege_id' => '',
                        'form_user_id' => $userId,
                        'to_user_id' => $tmpNextOrderProcessCourseRow->uid,
                        'foreign_key' => $foreignKey,
                        'type' => 9,
                        'type_id' => $orderProcessInfo['id'],
                        'title' => $tmpOrderTitle,
                        'content' => $messageContent,
                        'theme' => "{$tmpOrderTitle}已开工",
                    ];
                    UserMessage::sendCustomerOrderMessage($data);
                }
            }


            $orderProcessCourseObj->estimated_time_hour = $input['estimated_time_hour'];
            $orderProcessCourseObj->estimated_time_minute = $input['estimated_time_minute'];
            $orderProcessCourseObj->start_time = time();
            $orderProcessCourseObj->status = 3;
            $orderProcessCourseObj->uid = $userId;
            $orderProcessCourseObj->save();

            //修改工单列表关联表数据状态
            $type = 4;//工序工单
            $relateId = $orderProcessCourseObj->id;
            $status = 3;
            OrderEngine::changeOrderListRelationStatus($type, $relateId, $status);

            //员工开工后，修改工序工单状态
            $orderProcessObj = OrderProcess::where('id', $orderProcessId)->first();
            if ($orderProcessObj->status == 1 || $orderProcessObj->status == 2 || $orderProcessObj->status == 101) {
                $orderProcessObj->status = 3;
                $orderProcessObj->save();

                //修改工单列表关联表数据状态
                $type = 2;
                $relateId = $orderProcessObj->id;
                $status = 3;
                OrderEngine::changeOrderListRelationStatus($type, $relateId, $status);
            }


            //员工开工后，修改主工单状态
            $orderObj = Order::where('id', $orderId)->first();
            if ($orderObj->status == 1 || $orderObj->status == 101) {
                $orderObj->status = 2;
                $orderObj->save();

                //修改工单列表关联表数据状态
                $type = 1;
                $relateId = $orderObj->id;
                $status = 2;
                OrderEngine::changeOrderListRelationStatus($type, $relateId, $status);

                //修改订单状态
                $customerOrderId = $orderObj->customer_order_id;
                \App\Engine\OrderEngine::changeCustomerOrderStatus($customerOrderId, 4);//修改状态为生产中

            }
        }


        return '操作成功';
    }

    //确认开工后工单详情页面
    public function afterOrderDetail(Request $request)
    {
        //获取传入数据
        $input = $request->all();
        $input['order_process_id'] = isset($input['order_process_id']) ? $input['order_process_id'] : '';
        $input['order_process_course_id'] = isset($input['order_process_course_id']) ? $input['order_process_course_id'] : '';

        $userId = Func::getHeaderValueByName('userid');
        $userInfo = DepartmentUser::getCurrentInfo($userId)->toArray();
        $companyId = $userInfo['company_id'];

        //逻辑调整传入的id实际为员工工单id
        if ($input['order_process_course_id']) {
            $orderProcessCourseId = $input['order_process_course_id'];
            $orderProcessCourseRow = OrderProcessCourse::where(['id' => $orderProcessCourseId])->first()->toArray();
            $orderProcessId = $orderProcessCourseRow['order_process_id'];
            $input['order_process_id'] = $orderProcessId;
        } else {
            $orderProcessId = $input['order_process_id'];
        }

        //校验参数
        $rules = [
            'order_process_id' => 'required',
        ];
        $messages = [
            'order_process_id.required' => '缺少工单id',
        ];
        $this->validateRequestParameters($input, $rules, true, $messages);


        //获取对应工单工序表信息
        $orderProcessInfo = OrderProcess::where('id', $orderProcessId)->first()->toArray();
        //获取工单信息
        $orderInfo = Order::where('id', $orderProcessInfo['order_id'])->first()->toArray();
        //获取工序名称
        $processTitle = Process::getOneValueById($orderProcessInfo['process_type'], 'title');

        $processFieldList = Process::getFieldListByProcessId($orderProcessInfo['process_type']);


        //获取用户的权限
        $userId = Func::getHeaderValueByName('userid');
        $userRights = PermissionEngine::getUserStepPrivilegeByProcess($userId, $orderProcessInfo['process_type'], $orderInfo['order_type'])->toArray();
        if (count($userRights) == 1 && $userRights[0] == 1) {//只限制查看权限的用户
            //获取用户的角色id,角色例如为‘淋膜员工’
            $curUserInfo = DepartmentUser::getCurrentInfo($userId)->toArray();
            $privilegeId = $curUserInfo['privilege_id'];
            $processFieldList = PermissionEngine::getlookActionPrivilegeFieldsByProcessOrderType($orderInfo['order_type'], $orderProcessInfo['process_type'], $privilegeId);
        } else {
            $processFieldList = Process::getFieldListByProcessId($orderProcessInfo['process_type']);
        }


        $apeList = [];
        //追加工单基础信息
        $processOrderTypeId = $orderProcessInfo['ordertype_process_id'];//工序工单
        $privilegeId = $userInfo['privilege_id'];//角色id
        $baseFieldList = PermissionEngine::getBasePrivilegeFieldsByProcessOrderType($processOrderTypeId, $privilegeId);

        foreach ($baseFieldList as $baseFieldRow) {
            $showTitle = '';
            if (isset($orderInfo[$baseFieldRow['field_name']])) {
                $showTitle = $orderInfo[$baseFieldRow['field_name']];//默认展示字段的内容
            }

            $tmpFiledType = \App\Eloquent\Ygt\OrderFieldCompany::getFieldTypeByFieldName($baseFieldRow['field_name'], $companyId);
            $showTitle = OrderEngine::getOrderFiledValueTrue($orderInfo[$baseFieldRow['field_name']], $tmpFiledType);

            $apeList[] = [
                '$leftLabelValue' => $baseFieldRow['title'],
                '$rightLabelValue' => $showTitle,
            ];

        }

        foreach ($processFieldList as $processFieldRow) {
            if ($processFieldRow['field_name'] == 'remark') {//备注另外处理
                continue;
            }
            //通过字段类型不同处理
            //获取字段对应的类型1=>'文本',2=>'文本域',3=>'下拉框-跳界面',4=>'跳材料',5=>'有单位',6=>'开关',7=>'时间'
            $tmpFiledType = ProcessField::getFieldTypeByFieldName($processFieldRow['field_name'], $companyId);
            $showTitle = $orderProcessInfo[$processFieldRow['field_name']];//默认展示字段的内容

            $showTitle = OrderEngine::getOrderFiledValueTrue($orderProcessInfo[$processFieldRow['field_name']], $tmpFiledType);

            //工单的需完成数量改为员工被派发的数量
            if ($input['order_process_course_id']) {
                if ($processFieldRow['field_name'] == 'completed_number') {//需完成数量，员工使用被分配的数量
                    $showTitle = $orderProcessCourseRow['total_number'];
                }
            }


            //版跳转问题
            $plateId = 0;
            if ($tmpFiledType == 17 && $orderProcessInfo[$processFieldRow['field_name']]) {
                $tmpCreateOrderPlateId = $orderProcessInfo[$processFieldRow['field_name']];
                $tmpCreateOrderPlateRow = \App\Eloquent\Ygt\CreateOrderPlate::where(['id'=>$tmpCreateOrderPlateId])->first();
                $tmpCreateOrderPlateRowContent =json_decode(htmlspecialchars_decode($tmpCreateOrderPlateRow['content']), true);
                //显示固定版、套版组合
                if(isset($tmpCreateOrderPlateRowContent['branch']['fixed_plate'])){
                    $tmpReList = \App\Engine\OrderEngine::getOrderPlateDealInfo($tmpCreateOrderPlateRowContent,$processFieldRow['title']);
                    foreach ($tmpReList as $tmpReRow){
                        $apeList[] = $tmpReRow;
                    }
                }
            }elseif($tmpFiledType == 22 && $orderProcessInfo[$processFieldRow['field_name']]){
                $tmpCreateOrderProcessProductId = $orderProcessInfo[$processFieldRow['field_name']];
                $tmpCreateOrderProcessProductRow = \App\Eloquent\Ygt\CreateOrderProcessProduct::where(['id'=>$tmpCreateOrderProcessProductId])->first();
                $tmpCreateOrderProcessProductRowContent =json_decode(htmlspecialchars_decode($tmpCreateOrderProcessProductRow['content']), true);
                if($tmpCreateOrderProcessProductRowContent){
                    //显示半成品信息
                    foreach ($tmpCreateOrderProcessProductRowContent as $tmpCreateOrderProcessProductRowContentRow){
                        $apeList[] = [
                            '$leftLabelValue' => $processFieldRow['title'],
                            '$rightLabelValue' => "【{$tmpCreateOrderProcessProductRowContentRow['number']}】{$tmpCreateOrderProcessProductRowContentRow['process_product_title']}",
                        ];
                    }
                }
            }
            else{
                $apeList[] = [
                    '$leftLabelValue' => $processFieldRow['title'],
                    '$rightLabelValue' => $showTitle,
                    '$plateId' => $plateId,
                ];
            }

        }

        //追加需完成数量
        $orderProcessNeedNum = \App\Engine\OrderEngine::getOrderPorcessNeedNum($orderProcessInfo['process_type'],$orderInfo);
        if ($orderProcessNeedNum) {

            //获取工艺单位
            $curProcessRow = \App\Eloquent\Ygt\Process::getInfo(['id' => $orderProcessInfo['process_type']])->toArray();
            if($curProcessRow['measurement_unit']){
                $curProcessMeasurementUnit = $curProcessRow['measurement_unit'];
            }else{
                $curProcessMeasurementUnit = '';
            }


            $apeList[] = [
                '$leftLabelValue' => '需完成数量',
                '$rightLabelValue' => $orderProcessNeedNum.$curProcessMeasurementUnit,
            ];
        }


        //添加计件工资
        if (isset($orderProcessId, $privilegeId, $orderProcessCourseId)) {
            //角色是否需要设置计件工资
            //是否显示金额相关的数据 true-隐藏  false-显示
            $orderProcessRow =
            $isHideMoneyData = OrderEngine::getHideMoneyDataByProcessId($orderProcessInfo['process_type']);
            if (!$isHideMoneyData) {
                $pieceWage = \App\Engine\OrderEngine::getEmployeePieceWage($orderProcessId, $privilegeId, $orderProcessCourseId);
                $apeList[] = [
                    '$leftLabelValue' => '计件工资',
                    '$rightLabelValue' => $pieceWage ? $pieceWage : '未设置',
                ];
            }
        }


        //这个页面新加个按钮,可以成品入库

        //获取员工的角色id，判断是否可以成品入库 20180702
        $ableFinishedProduct = 0;
        if ($input['order_process_course_id']) {
            $orderProcessCourseId = $input['order_process_course_id'];
            $orderProcessCourseRow = OrderProcessCourse::where(['id' => $orderProcessCourseId])->first()->toArray();
            $personnelId = $orderProcessCourseRow['uid'];
            $personnelRow = DepartmentUser::getCurrentInfo($personnelId)->toArray();
            $personnelPrivilegeId = $personnelRow['privilege_id'];

            $ableFinishedProduct = OrderEngine::getPrivilegeFinishedProduct($personnelPrivilegeId, $orderProcessInfo['ordertype_process_id']);
//            if ($ableFinishedProduct) {
//                $finishNumber = $orderProcessCourseRow['finish_number'];
//                //已提交数量
//                $finishedProductNum = $orderProcessCourseRow['finished_product_num'];
//                if ($finishNumber > $finishedProductNum) {
//                    $ableFinishedProduct = 1;
//                } else {
//                    $ableFinishedProduct = 0;
//                }
//            } else {
//                $ableFinishedProduct = 0;
//            }

            //先不判断是否需要入库，都显示成品入库按钮
            if($ableFinishedProduct){
                $ableFinishedProduct = 1;
            }else{
                $ableFinishedProduct = 0;
            }

        }


        //如果是员工工单，追加数据完成数量 zhuyujun 20180823
        $submitList = [];
        if ($input['order_process_course_id']) {
            //分批提交数量展示
            $where = [
                ['order_process_course_id', '=', $input['order_process_course_id']],
                ['submit_num', '>', 0],
            ];
            $orderProcessCourseGradationList = \App\Eloquent\Ygt\OrderProcessCourseGradation::where($where)->get();

            $submitNumAll = 0;
            foreach ($orderProcessCourseGradationList as $orderProcessCourseGradationRow) {
                $tmpArr = [
                    'submit_date' => date('Y.m.d', $orderProcessCourseGradationRow['submit_time']),
                    'submit_num' => $orderProcessCourseGradationRow['submit_num'],
                    'submit_wages' => '',

                ];
                $submitNumAll += $orderProcessCourseGradationRow['submit_num'];
                $submitList[] = $tmpArr;
            }

            if($submitNumAll){
                $submitList[] = [
                    'submit_date' => '合计',
                    'submit_num' => $submitNumAll,
                    'submit_wages' => '',
                ];
            }
        }


        //返回ape填充数据
        $returnApe = [
            'pageID' => 8,
            'data' => [
                '$titleLabelValue' => $processTitle,
                '$commentValue' => $orderProcessInfo['remark'],
                '$list' => $apeList,
                '$submitList' => $submitList,
            ],
            'able_finished_product' => $ableFinishedProduct,//是否有成品入库按钮 1-有 0-无
            'submit_material_id' => $orderProcessInfo['id'],//提交用料时所需传的ID
            'able_submit_material' => 1,//是否可以提交用料
        ];

        return $returnApe;
    }

    //领取材料页面基础页面
    public function confirmReceiveMaterialBaseInfo(Request $request)
    {
        //获取传入数据
        $input = $request->all();
        $input['order_process_id'] = isset($input['order_process_id']) ? $input['order_process_id'] : '';
        $input['order_process_course_id'] = isset($input['order_process_course_id']) ? $input['order_process_course_id'] : '';

        if ($input['order_process_course_id']) {
            $input['order_process_id'] = $input['order_process_course_id'];
        }

        //逻辑调整传入的id实际为员工工单id
        $orderProcessCourseId = $input['order_process_id'];
        $orderProcessCourseRow = OrderProcessCourse::where(['id' => $orderProcessCourseId])->first()->toArray();

        //获取对应工序信息
        $orderProcessInfo = OrderProcess::where('id', $orderProcessCourseRow['order_process_id'])->first()->toArray();
        //获取工单信息
        $orderInfo = Order::where('id', $orderProcessInfo['order_id'])->first()->toArray();
        //获取工序名称
        $processTitle = Process::getOneValueById($orderProcessInfo['process_type'], 'title');

        //获取工单创建时设置的材料
        $fields = [
            'ygt_order_material_course.*',
            'ygt_product.product_name',
            'ygt_product.unit'
        ];
        $orderMaterialCollection = OrderMaterialCourse::where(['order_process_course_id' => $orderProcessCourseId, 'process_type' => $orderProcessInfo['process_type']])->leftJoin('ygt_product', 'ygt_order_material_course.material_id', '=', 'ygt_product.id')->select($fields)->get();
        $orderMaterialList = [];
        foreach ($orderMaterialCollection as $tmpRow) {
            $tmpOrderMaterialRow = $tmpRow->toArray();
            $tmpMateriaRow = ProductEngine::getProductInfoExist($tmpOrderMaterialRow['material_id']);
            if ($tmpMateriaRow) {
                $tmpOrderMaterialRow['product_no'] = $tmpMateriaRow['product_no'];
                $tmpOrderMaterialRow['is_trash'] = 0;
                $orderMaterialList[] = $tmpOrderMaterialRow;
            } else {
                //删除材料处理
                $tmpMateriaRow = ProductEngine::getProductInfoTrash($tmpOrderMaterialRow['material_id']);
                $tmpOrderMaterialRow['is_trash'] = 1;
                $tmpOrderMaterialRow['product_name'] = $tmpMateriaRow['product_name'] . "[材料已删除]";

                $orderMaterialList[] = $tmpOrderMaterialRow;
            }
        }

        //处理图片数据
        $imgIdList = explode(',', $orderInfo['production_case_diagram']);
        $exampleImg = '';
        $imgNum = 0;
        foreach ($imgIdList as $imgId) {
            if (!trim($imgId)) {//过滤空格 图片id应该不会有0
                continue;
            }
            $imgNum++;
            if (!$exampleImg) {//取第一张图作为示例图
                $exampleImg = ImgUpload::getImgUrlById($imgId);
            }
        }

        //获取上一个部门&上一个部门
        $preProcessList = OrderType::getAllPrevOrderProcess($orderInfo['order_type'], $orderProcessInfo['process_type'])->toArray();
        //获取预估完成时间最晚的一个，待开工的部门优先级最高
        $preProcess = '';//上一个工序（部门）
        $preProcessEstimatedTime = 0;
        $preProcessEstimatedTimeStr = '';
        $lastOrderProcessId = 0;
        $finishNum = 0;
        if ($preProcessList) {
            foreach ($preProcessList as $processId) {
                //获取工序信息
                $preOrderProcessInfo = OrderProcess::where(['order_id' => $orderInfo['id'], 'process_type' => $processId])->first()->toArray();
                $preProcess = Process::getOneValueById($preOrderProcessInfo['process_type'], 'title');
                $processIsSum = Process::getOneValueById($preOrderProcessInfo['process_type'], 'is_sum');

                $lastOrderProcessId = $preOrderProcessInfo['id'];
                if ($preOrderProcessInfo['status'] == 1) {//待开工
                    $preProcessEstimatedTimeStr = '待开工';
                    break;
                } else {
                    //获取员工工单列表
                    //调整-预计完成时间调整为从员工工单获取
                    $orderProcessCourseList = OrderProcessCourse::where(['order_process_id' => $preOrderProcessInfo['id']])->get();
                    $finishNum = 0;
                    foreach ($orderProcessCourseList as $orderProcessCourseRow) {

                        $tmpPreProcessEstimatedTime = $orderProcessCourseRow['start_time'] + $orderProcessCourseRow['estimated_time_hour'] * 3600 + $orderProcessCourseRow['estimated_time_minute'] * 60;
                        if ($tmpPreProcessEstimatedTime > $preProcessEstimatedTime) {
                            $preProcessEstimatedTime = $tmpPreProcessEstimatedTime;
                            $preProcessEstimatedTimeStr = '' . date('Y年m月d日 H时', $preProcessEstimatedTime);
                        }


                        //设定的角色不进行统计数量到工序数量中
                        //过滤异常数据
                        if (!DepartmentUser::getCurrentInfo($orderProcessCourseRow['uid'])) {
                            continue;
                        }
                        $tmpUserInfo = DepartmentUser::getCurrentInfo($orderProcessCourseRow['uid'])->toArray();
                        $tmpPrivilegeId = $tmpUserInfo['privilege_id'];
                        if (OrderEngine::getProcessNumNoStatistics($tmpPrivilegeId)) {
                            continue;
                        }

                        $finishNum += $orderProcessCourseRow['finish_number'];
                        if (!$processIsSum) {//不累加
                            $tmpUserInfo = DepartmentUser::getCurrentInfo($orderProcessCourseRow['uid'])->toArray();
                            $tmpPrivilegeId = $tmpUserInfo['privilege_id'];
                            if (isset($finishUserNumList[$tmpPrivilegeId])) {
                                $finishUserNumList[$tmpPrivilegeId]['finish_number'] += $orderProcessCourseRow['finish_number'];
                            } else {
                                $finishUserNumList[$tmpPrivilegeId]['finish_number'] = $orderProcessCourseRow['finish_number'];
                            }
                        }
                    }


                    if ($preProcessEstimatedTime < 631152000) {//过滤1970的情况
                        $preProcessEstimatedTimeStr = '';
                    }


                    //不累加--未完工时取完成量最小的员工
                    if (!empty($finishUserNumList)) {
                        $finishMinNum = '';
                        foreach ($finishUserNumList as $finishUserNumRow) {
                            if ($finishMinNum === 0) {//如果有员工完成数量为0，
                                break;
                            }

                            if ($finishUserNumRow['finish_number'] < $finishMinNum || $finishMinNum === '') {//如果有员工完成数量更少，或者第一个员工的数据
                                $finishMinNum = $finishUserNumRow['finish_number'];
                            }
                        }
                        $finishNum = $finishMinNum;
                    }


                    if ($preOrderProcessInfo['status'] == 4) {//追加该部门完成数量
//                        $preProcessEstimatedTimeStr .= " 完成数量:" . $finishNum;
                    }

                }
            }
        } else {
            $preProcess = '无';//上一个工序（部门）
            $preProcessEstimatedTimeStr = '';
        }

        //获取领材是否需要扫码的配置
        $companyId = $orderInfo['company_id'];//厂id
        $isScanCode = Company::isScanCode($companyId);

        //获取工序类型名称
        $orderTypeTitle = OrderType::getOneValueById($orderInfo['order_type'], 'title');

        $orderInfo['order_title'] = \App\Engine\Common::changeSnCode($orderInfo['order_title']);

        $return = [];
        $return['product_name'] = $orderTypeTitle;//产品名称
        $return['order_title'] = $orderInfo['order_title'];//生产单号
        $return['finished_date'] = $orderInfo['finished_date'];//交货日期
        $return['estimated_time'] = $preProcessEstimatedTimeStr;//预计完成
        $return['last_order_process_finish_num'] = $finishNum;//上一工序完成数量
        $return['img_url'] = $exampleImg;//示例图
        $return['img_title'] = '共' . $imgNum . '张图片';//示例图文字提示
        $return['last_department'] = $preProcess;//上一部门
        $return['last_order_process_id'] = $lastOrderProcessId;//上一工序id
        $return['jump_tips'] = '已接单[' . $processTitle . ']';//跳转到工单详情文字提示
        $return['order_material_list'] = $orderMaterialList;//领取材料列表
        $return['img_order_id'] = $orderInfo['id'];//主工单id
        $return['is_scan_code'] = $isScanCode;//是否需要扫码领取材料

        return $return;
    }

    //确认领取材料数量
    public function confirmReceiveMaterial(Request $request)
    {
        //获取传入数据
        $input = $request->all();
        $input['order_process_id'] = isset($input['order_process_id']) ? $input['order_process_id'] : '';
        $input['material_id'] = isset($input['material_id']) ? $input['material_id'] : '';//领取的材料id
        $input['receive_number'] = isset($input['receive_number']) ? $input['receive_number'] : '';//领取的材料数量


        //判断领取数量是否大于材料库存
        $materialRow = \App\Engine\Product::getProductInfo($input['material_id']);
        if ($materialRow['number'] < $input['receive_number']) {
            return [
                'code' => 1,
                'message' => '库存不足' . "（现余库存{$materialRow['number']}）"
            ];
        }

        //逻辑调整传入的id实际为员工工单id
        $orderProcessCourseId = $input['order_process_id'];
        $orderProcessCourseRow = OrderProcessCourse::where(['id' => $orderProcessCourseId])->first()->toArray();

        //校验参数
        $rules = [
            'order_process_id' => 'required',
        ];
        $messages = [
            'order_process_id.required' => '缺少工单id',
        ];
        $this->validateRequestParameters($input, $rules, true, $messages);
        //获取对应工单工序表信息
        $orderProcessInfo = OrderProcess::where('id', $orderProcessCourseRow['order_process_id'])->first()->toArray();
        //数据入库
        //工单材料表（修改操作，新加材料走其他接口）
        $orderMaterialCourseObj = OrderMaterialCourse::where(['order_process_course_id' => $orderProcessCourseId, 'process_type' => $orderProcessInfo['process_type'], 'material_id' => $input['material_id']])->first();
        $orderMaterialCourseObj->receive_number = $input['receive_number'];
        $orderMaterialCourseObj->save();

        //仓库材料库存表
//        Stock::OrderProcessStockOut($orderProcessCourseId);

        return '领取成功';
    }

    //添加材料
    public function addMaterial(Request $request)
    {
        //获取传入数据
        $input = $request->all();
        $input['order_process_id'] = isset($input['order_process_id']) ? $input['order_process_id'] : '';
        $input['material_id'] = isset($input['material_id']) ? $input['material_id'] : '';//材料id
        $input['process_type'] = isset($input['process_type']) ? $input['process_type'] : '';//工单工序类型

        //逻辑调整传入的id实际为员工工单id
        $orderProcessCourseId = $input['order_process_id'];
        $orderProcessCourseRow = OrderProcessCourse::where(['id' => $orderProcessCourseId])->first()->toArray();

        //校验参数
        $rules = [
            'order_process_id' => 'required',
//            'material_id' => 'required',
        ];
        $messages = [
            'order_process_id.required' => '缺少工单id',
//            'material_id.required' => '缺少材料id',
        ];
        $this->validateRequestParameters($input, $rules, true, $messages);

        //获取用户id
        $userId = $orderProcessCourseRow['uid'];
        $userInfo = DepartmentUser::getCurrentInfo($userId)->toArray();
        $companyId = isset($userInfo['company_id']) ? $userInfo['company_id'] : '';

        //获取对应工单工序表信息
        $orderProcessInfo = OrderProcess::where('id', $orderProcessCourseRow['order_process_id'])->first()->toArray();
        //获取工单信息
        $orderInfo = Order::where('id', $orderProcessInfo['order_id'])->first()->toArray();
        //获取工序名称
        $processTitle = Process::getOneValueById($orderProcessInfo['process_type'], 'title');

        //添加新材料到数据库
        $materialIdList = explode(',', $input['material_id']);
        foreach ($materialIdList as $materialId) {
            if (trim($materialId)) {
                $orderMaterialObj = OrderMaterialCourse::firstOrCreate(
                    [
                        'order_process_course_id' => $orderProcessCourseId,
                        'order_process_id' => $orderProcessInfo['id'],
                        'process_type' => $orderProcessInfo['process_type'],
                        'material_id' => $materialId,
                        'company_id' => $companyId
                    ], ['allow_delete' => 1]);
                /*$orderMaterialRow = [
                    'order_id' => $orderProcessInfo['order_id'],
                    'process_type' => $orderProcessInfo['process_type'],
                    'material_id' => $materialId,
                    'allow_delete' => 1,
                ];
                $orderMaterialObj->fill($orderMaterialRow);*/
//                $orderMaterialObj->save();
            }
        }
        return '添加成功';
    }

    //添加材料
    public function manageMaterial(Request $request)
    {
        //获取传入数据
        $input = $request->all();
        $input['order_process_id'] = isset($input['order_process_id']) ? $input['order_process_id'] : '';
        $input['material_id'] = isset($input['material_id']) ? $input['material_id'] : '';//材料id
        $input['process_type'] = isset($input['process_type']) ? $input['process_type'] : '';//工单工序类型

        //校验参数
        $rules = [
            'order_process_id' => 'required',
        ];
        $messages = [
            'order_process_id.required' => '缺少工单id',
        ];
        $this->validateRequestParameters($input, $rules, true, $messages);


        //获取对应工单工序表信息
        $orderProcessInfo = OrderProcess::where('id', $input['order_process_id'])->first()->toArray();
        //获取工单信息
        $orderInfo = Order::where('id', $orderProcessInfo['order_id'])->first()->toArray();
        //获取工序名称
        $processTitle = Process::getOneValueById($orderProcessInfo['process_type'], 'title');

        //添加新材料到数据库
        $materialIdList = explode(',', $input['material_id']);
        foreach ($materialIdList as $materialId) {
            if (trim($materialId)) {
                $orderMaterialObj = OrderMaterial::firstOrCreate(['order_id' => $orderProcessInfo['order_id'], 'process_type' => $orderProcessInfo['process_type'], 'material_id' => $materialId], ['allow_delete' => 1]);
            }
        }
        //删除未传入材料的id的原纪录
        OrderMaterial::where(['order_id' => $orderProcessInfo['order_id'], 'process_type' => $orderProcessInfo['process_type']])->whereNotIn($materialIdList)->delete();

        return '添加成功';
    }

    //删除材料
    public function deleteMaterial(Request $request)
    {

        $userId = \App\Engine\Func::getHeaderValueByName('userid');
        $userInfo = \App\Eloquent\Ygt\DepartmentUser::getCurrentInfo($userId)->toArray();

        //获取传入数据
        $input = $request->all();
        $input['order_process_id'] = isset($input['order_process_id']) ? $input['order_process_id'] : '';
        $input['material_id'] = isset($input['material_id']) ? $input['material_id'] : '';//材料id

        //逻辑调整传入的id实际为员工工单id
        $orderProcessCourseId = $input['order_process_id'];
        $orderProcessCourseRow = OrderProcessCourse::where(['id' => $orderProcessCourseId])->first()->toArray();

        //校验参数
        $rules = [
            'order_process_id' => 'required',
            'material_id' => 'required',
        ];
        $messages = [
            'order_process_id.required' => '缺少工单id',
            'material_id.required' => '缺少材料id',
        ];
        $this->validateRequestParameters($input, $rules, true, $messages);


        //获取对应工单工序表信息
        $orderProcessInfo = OrderProcess::where('id', $orderProcessCourseRow['order_process_id'])->first()->toArray();

//        //删除材料
//        $orderMaterialObj = OrderMaterialCourse::firstOrNew(['order_process_course_id' => $orderProcessCourseId, 'process_type' => $orderProcessInfo['process_type'], 'material_id' => $input['material_id']]);
//        $orderMaterialObj->delete();

        //删除分次提交记录
        $tmpObjList = \App\Eloquent\Ygt\OrderMaterialReceiveGradation::where(['material_id'=>$input['material_id'],'order_process_course_id'=>$orderProcessCourseId])->get();
        foreach ($tmpObjList as $tmpObj){
            $tmpObj->delete();
        }


        //材料回退
        Stock::OrderMateialDeleteStockIn($orderProcessCourseId,$input['material_id'],$userId);


        return '删除成功';
    }


    //确认领取完成
    public function confirmReceiveComplete(Request $request)
    {
        //获取传入数据
        $input = $request->all();
        $input['order_process_id'] = isset($input['order_process_id']) ? $input['order_process_id'] : '';//实际为员工工单ID

        //逻辑调整传入的id实际为员工工单id
        $orderProcessCourseId = $input['order_process_id'];
        $orderProcessCourseRow = OrderProcessCourse::where(['id' => $orderProcessCourseId])->first()->toArray();
        

        //校验参数
        $rules = [
            'order_process_id' => 'required',
        ];
        $messages = [
            'order_process_id.required' => '缺少工单id',
        ];
        $this->validateRequestParameters($input, $rules, true, $messages);

        //获取对应工单工序表信息
        $orderProcessInfo = OrderProcess::where('id', $orderProcessCourseRow['order_process_id'])->first()->toArray();
        $orderId = $orderProcessInfo['order_id'];
        $order = Order::where('id', $orderId)->first();
        $foreignKey = intval($order->customer_order_id);

        //如果材料有未领取不能完成
        $orderMaterialList = OrderMaterialCourse::where(['order_process_course_id' => $orderProcessCourseId, 'process_type' => $orderProcessInfo['process_type']])->get()->toArray();
        if (!empty($orderMaterialList)) {

            $companyId = $messageContent = '';
            foreach ($orderMaterialList as $orderMaterialRow) {
                if($orderMaterialRow['status']){
                    return [
                        'code' => 1,
                        'message' => '请勿重复领取材料'
                    ];
                }


                if (!$orderMaterialRow['receive_number']) {
                    return [
                        'code' => 1,
                        'message' => '请领取完材料'
                    ];
                }

                //判断库存数量是否足够
                $materialId = $orderMaterialRow['material_id'];
                $stockInfo = ProductEngine::getProductInfo($materialId);
                if ($stockInfo['number'] < $orderMaterialRow['receive_number']) {
                    return [
                        'code' => 1,
                        'message' => '材料' . $stockInfo['product_name'] . '库存不足'
                    ];
                }

                $companyId = $orderMaterialRow['company_id'];
                $messageContent .= ',' . $stockInfo['product_name'];
            }


            //判断领取材料
            Stock::OrderProcessCourseStockOut($orderProcessCourseId);
        }

        //修改工单工序状态
        $orderProcessCourseObj = OrderProcessCourse::where('id', $orderProcessCourseId)->first();
        $orderProcessCourseObj->status = 1;
        $orderProcessCourseObj->receive_material_time = time();
        $orderProcessCourseObj->save();

        //修改工单列表关联表数据状态
        $type = 4;
        $relateId = $orderProcessCourseObj->id;
        $status = 1;
        OrderEngine::changeOrderListRelationStatus($type, $relateId, $status);

        //修改工单材料状态
        $tmpOrderMaterialObjList = OrderMaterialCourse::where(['order_process_course_id' => $orderProcessCourseId, 'process_type' => $orderProcessInfo['process_type']])->get();
        foreach ($tmpOrderMaterialObjList as $tmpOrderMaterialObj){
            $tmpOrderMaterialObj->status = 1;
            $tmpOrderMaterialObj->save();
        }


        //修改消息状态
        $typeId = $orderProcessCourseObj->id;
        $typeUserId = $orderProcessCourseObj->uid;
        UserMessage::updateTypeStatusByTypeId(1, $typeId, $typeUserId, 1);

        //如果工序订单状态为接单，修改状态
        $orderProcessId = $orderProcessInfo['id'];
        $orderProcessObj = OrderProcess::where(['id' => $orderProcessId])->first();
        if ($orderProcessObj->status == 1) {
            // 修改工序工单状态为2（已接单）
            $orderProcessObj->status = 2;
            $orderProcessObj->save();
        }


        ////发送消息给下单人领取情况
        $userId = Func::getHeaderValueByName('userid');

        //判断用户是否为管理员
        $userInfo = DepartmentUser::getCurrentInfo($userId)->toArray();
        $companyId = isset($userInfo['company_id']) ? $userInfo['company_id'] : '';


        $messageContent = '领取了材料';

        $messageContent .= '【工单号: ' . $order['order_title'] . '】';
        $data = [
            'company_id' => $companyId,
            'privilege_id' => '',
            'form_user_id' => $userId,
            'to_user_id' => $order['uid'],
            'foreign_key' => $foreignKey,
            'type' => 32,//艺管理员领取材料时发送消息给下单人
            'type_id' => $orderProcessInfo['id'],
            'title' => $order['order_title'],
            'content' => $messageContent
        ];
        UserMessage::sendCustomerOrderMessage($data);


        return '确认领取完成';
    }

    //确认完工基础页面信息
    public function confirmCompleteBaseInfo(Request $request)
    {
        $userId = Func::getHeaderValueByName('userid');
        $userInfo = DepartmentUser::getCurrentInfo($userId)->toArray();

        //获取传入数据
        $input = $request->all();
        $input['order_process_id'] = isset($input['order_process_id']) ? $input['order_process_id'] : '';
        $input['order_process_course_id'] = isset($input['order_process_course_id']) ? $input['order_process_course_id'] : '';
        $inputType = isset($input['type']) ? $input['type'] : 0;

        if ($input['order_process_course_id']) {
            $input['order_process_id'] = $input['order_process_course_id'];
        }

        //逻辑调整传入的id实际为员工工单id
        $orderProcessCourseId = $input['order_process_id'];
        $orderProcessCourseRow = OrderProcessCourse::where(['id' => $orderProcessCourseId])->first()->toArray();
        $totalNumber = $orderProcessCourseRow['total_number'];
        $finishNumber = $orderProcessCourseRow['finish_number'];
        $wasteNumber = $orderProcessCourseRow['waste_number'];
        if (!$finishNumber) {
            $finishNumber = 0;
        }
        if (!$wasteNumber) {
            $wasteNumber = 0;
        }

        //校验参数
        $rules = [
            'order_process_id' => 'required',
        ];
        $messages = [
            'order_process_id.required' => '缺少工单id',
        ];
        $this->validateRequestParameters($input, $rules, true, $messages);


        //获取对应工单工序表信息
        $orderProcessInfo = OrderProcess::where('id', $orderProcessCourseRow['order_process_id'])->first()->toArray();

        //获取工单信息
        $orderInfo = Order::where('id', $orderProcessInfo['order_id'])->first()->toArray();
        //获取工序名称
        $processInfo = Process::getOneValueById($orderProcessInfo['process_type'], ['title','measurement_unit']);
        $processTitle = $processInfo['title'];
        $processMeasurementUnit = $processInfo['measurement_unit'];

        ////员工不再领取提交材料 zhuyujun 20180707
        $orderMaterialList = [];

        //处理图片数据
        $imgIdList = explode(',', $orderInfo['production_case_diagram']);
        $exampleImg = '';
        $imgNum = 0;
        foreach ($imgIdList as $imgId) {
            if (!trim($imgId)) {//过滤空格 图片id应该不会有0
                continue;
            }
            $imgNum++;
            if (!$exampleImg) {//取第一张图作为示例图
                $exampleImg = ImgUpload::getImgUrlById($imgId);
            }
        }


        //获取上一个部门&上一个部门
        $preProcessList = OrderType::getAllPrevOrderProcess($orderInfo['order_type'], $orderProcessInfo['process_type'])->toArray();
        //获取预估完成时间最晚的一个，待开工的部门优先级最高
        $preProcess = '';//上一个工序（部门）
        $preProcessEstimatedTime = 0;
        $preProcessEstimatedTimeStr = '';
        $lastOrderProcessId = 0;
        $finishNum = 0;
        $preProcessMeasurementUnit = '';
        $isPreEmpty = 0;

        if ($preProcessList) {
            foreach ($preProcessList as $processId) {
                //获取工序信息
                $tmpOrderProcessInfo = OrderProcess::where(['order_id' => $orderInfo['id'], 'process_type' => $processId])->first()->toArray();
                $lastOrderProcessId = $tmpOrderProcessInfo['id'];

                //获取工序数量是否需要叠加&工序名称
                $where = ['id' => $processId];
                $process = Process::getInfo($where)->toArray();
                $preProcess = $process['title'];//工序名称
                $processIsSum = $process['is_sum'];//工序数量是否累加 0-不累加 1-累加

                if ($tmpOrderProcessInfo['status'] == 1) {//待开工
                    $preProcessEstimatedTimeStr = '待开工';
                    break;
                } else {

                    //调整-预计完成时间调整为从员工工单获取
                    $orderProcessCourseList = OrderProcessCourse::where(['order_process_id' => $tmpOrderProcessInfo['id']])->get();
                    $finishNum = 0;

                    $finishUserNumList = [];
                    foreach ($orderProcessCourseList as $orderProcessCourseRow) {


                        $tmpPreProcessEstimatedTime = $orderProcessCourseRow['start_time'] + $orderProcessCourseRow['estimated_time_hour'] * 3600 + $orderProcessCourseRow['estimated_time_minute'] * 60;
                        if ($tmpPreProcessEstimatedTime > $preProcessEstimatedTime) {
                            $preProcessEstimatedTime = $tmpPreProcessEstimatedTime;
                            $preProcessEstimatedTimeStr = date('Y年m月d日H时', $preProcessEstimatedTime);
                        }

                        //设定的角色不进行统计数量到工序数量中
                        //过滤异常数据
                        if (!DepartmentUser::getCurrentInfo($orderProcessCourseRow['uid'])) {
                            continue;
                        }
                        $tmpUserInfo = DepartmentUser::getCurrentInfo($orderProcessCourseRow['uid'])->toArray();
                        $tmpPrivilegeId = $tmpUserInfo['privilege_id'];
                        if (OrderEngine::getProcessNumNoStatistics($tmpPrivilegeId)) {
                            continue;
                        }

                        $finishNum += $orderProcessCourseRow['finish_number'];
                        if (!$processIsSum) {//不累加
                            $tmpUserInfo = DepartmentUser::getCurrentInfo($orderProcessCourseRow['uid'])->toArray();
                            $tmpPrivilegeId = $tmpUserInfo['privilege_id'];
                            if (isset($finishUserNumList[$tmpPrivilegeId])) {
                                $finishUserNumList[$tmpPrivilegeId]['finish_number'] += $orderProcessCourseRow['finish_number'];
                            } else {
                                $finishUserNumList[$tmpPrivilegeId]['finish_number'] = $orderProcessCourseRow['finish_number'];
                            }
                        }
                    }


                    if ($preProcessEstimatedTime < 631152000) {//过滤1970的情况
                        $preProcessEstimatedTimeStr = '';
                    }

                    //不累加--未完工时取完成量最小的员工
                    if (!empty($finishUserNumList)) {
                        $finishMinNum = '';
                        foreach ($finishUserNumList as $finishUserNumRow) {
                            if ($finishMinNum === 0) {//如果有员工完成数量为0，
                                break;
                            }

                            if ($finishUserNumRow['finish_number'] < $finishMinNum || $finishMinNum === '') {//如果有员工完成数量更少，或者第一个员工的数据
                                $finishMinNum = $finishUserNumRow['finish_number'];
                            }
                        }
                        $finishNum = $finishMinNum;
                        $preProcessMeasurementUnit = $process['measurement_unit'];
                    }


                    if ($tmpOrderProcessInfo['status'] == 4) {//追加该部门完成数量
//                        $preProcessEstimatedTimeStr .= " 完成数量:" . $finishNum;
                    }
                }
            }
        } else {
            $preProcess = '无';//上一个工序（部门）
            $preProcessEstimatedTimeStr = '';
            $isPreEmpty = 1;
        }

        //分批提交数量展示
        $where = [
            ['order_process_course_id', '=', $orderProcessCourseId],
            ['submit_num', '>', 0],
        ];
        $orderProcessCourseGradationList = OrderProcessCourseGradation::where($where)->get();
        $submitList = [];
        foreach ($orderProcessCourseGradationList as $orderProcessCourseGradationRow) {
            $tmpArr = [
                'id' => $orderProcessCourseGradationRow['id'],
                'submit_date' => date('Y.m.d', $orderProcessCourseGradationRow['submit_time']),
                'submit_num' => $orderProcessCourseGradationRow['submit_num']
            ];
            $submitList[] = $tmpArr;
        }

        //分批提交废品数量展示
        $where = [
            ['order_process_course_id', '=', $orderProcessCourseId],
            ['submit_waste_num', '>', 0],
        ];
        $orderProcessCourseGradationList = OrderProcessCourseGradation::where($where)->get();
        $submitWasteList = [];
        foreach ($orderProcessCourseGradationList as $orderProcessCourseGradationRow) {
            $tmpArr = [
                'id' => $orderProcessCourseGradationRow['id'],
                'submit_date' => date('Y.m.d', $orderProcessCourseGradationRow['submit_time']),
                'submit_num' => $orderProcessCourseGradationRow['submit_waste_num']
            ];
            $submitWasteList[] = $tmpArr;
        }

        //获取工序类型名称
        $orderTypeTitle = OrderType::getOneValueById($orderInfo['order_type'], 'title');


        //获取员工的角色id，判断是否需要输入件数 20180323
        $orderProcessCourseId = $input['order_process_id'];
        $orderProcessCourseRow = OrderProcessCourse::where(['id' => $orderProcessCourseId])->first()->toArray();
        $personnelId = $orderProcessCourseRow['uid'];
        $personnelRow = DepartmentUser::getCurrentInfo($personnelId)->toArray();
        $personnelPrivilegeId = $personnelRow['privilege_id'];

        $needPiece = OrderEngine::getPrivilegePiece($personnelPrivilegeId, $orderProcessInfo['ordertype_process_id']);

        $ableFinishedProduct = 0;
        $tmpAbleFinishedProduct = OrderEngine::getPrivilegeFinishedProduct($personnelPrivilegeId, $orderProcessInfo['ordertype_process_id']);
        if ($tmpAbleFinishedProduct) { //格式统一 1--可以 0--禁止
            $ableFinishedProduct = 1;
        }


        $ableUpdateSubmitNum = 0;
        //工序管理员允许修改提交数量
        if ($userId == $orderProcessInfo['uid']) {
            $ableUpdateSubmitNum = 1;
        }

        //是否显示领取材料按钮
        $isAbleReceiveMaterial = 1;
        if($orderProcessInfo['status'] ==  4){
            $isAbleReceiveMaterial = 0;
        }



        $orderInfo['order_title'] = \App\Engine\Common::changeSnCode($orderInfo['order_title']);


        $return = [];
        $return['product_name'] = $orderTypeTitle;//产品名称
        $return['order_title'] = $orderInfo['order_title'];//生产单号
        $return['finished_date'] = $orderInfo['finished_date'];//交货日期
        $return['estimated_time'] = $preProcessEstimatedTimeStr;//预计完成
        $return['last_order_process_finish_num'] = $finishNum.$preProcessMeasurementUnit;//上一工序完成数量
        $return['total_number'] = $totalNumber;//需完成数量
        $return['img_url'] = $exampleImg;//示例图
        $return['img_title'] = '共' . $imgNum . '张图片';//示例图文字提示
        $return['last_department'] = $preProcess;//上一部门
        $return['last_order_process_id'] = $lastOrderProcessId;//上一工序
        $return['jump_tips'] = '已接单[' . $processTitle . ']';//跳转到工单详情文字提示
        $return['order_material_list'] = $orderMaterialList;//领取材料列表
        $return['img_order_id'] = $orderInfo['id'];//主工单id
        $return['finish_number'] = $finishNumber;//已完成数量
        $return['waste_number'] = $wasteNumber;//已完成数量
        $return['submit_list'] = $submitList;//分次提交详情
        $return['submit_waste_list'] = $submitWasteList;//分次提交废品详情
        $return['needPiece'] = $needPiece;//是否需要填入件数
        $return['ableFinishedProduct'] = $ableFinishedProduct;//能否成品入库
        $return['ableUpdateSubmitNum'] = $ableUpdateSubmitNum;//能否修改完成（废品）数量 1-能修改 0-不能修改
        $return['receive_material_id'] = $orderProcessInfo['id'];//员工领取材料时所需的ID
        $return['is_pre_empty'] = $isPreEmpty;//1-没有上一工序 0-有
        $return['is_able_receive_material'] = $isAbleReceiveMaterial;//1-可以领取材料 0-隐藏领取材料
        $return['submit_material_id'] = $orderProcessInfo['id'];//提交用料时所需传的ID
        $return['able_submit_material'] = 1;//是否可以提交用料

//        $return['type'] = $inputType;//0简单版1车间版
//        if($inputType==1)
//        {
//            $return['img_title'] = '共x' . $imgNum . '张图片';
//        }

        return $return;

    }


    //确认完工
    public function confirmComplete(Request $request)
    {
        //获取登陆用户信息
        $userId = \App\Engine\Func::getHeaderValueByName('userid');
        $userInfo = \App\Eloquent\Ygt\DepartmentUser::getCurrentInfo($userId)->toArray();

        //获取传入数据
        $input = $request->all();
        $input['order_process_id'] = isset($input['order_process_id']) ? $input['order_process_id'] : '';
        $input['order_process_course_id'] = isset($input['order_process_course_id']) ? $input['order_process_course_id'] : '';
        $input['completed_number'] = isset($input['completed_number']) ? $input['completed_number'] : '';//完成数量
        $input['waste_number'] = isset($input['waste_number']) ? $input['waste_number'] : '';//废品数量
        $input['meter_counter'] = isset($input['meter_counter']) ? $input['meter_counter'] : '';//计米器图片
        $input['finish_number_piece'] = isset($input['finish_number_piece']) ? $input['finish_number_piece'] : '';//完成数量-件数
        $inputRemark = isset($input['remark']) ? $input['remark'] : '';//备注

        if ($input['material_list']) {
            $input['material_list'] = \GuzzleHttp\json_decode(htmlspecialchars_decode($input['material_list']), true);
        } else {
            $input['material_list'] = [];
        }

        if ($input['order_process_course_id']) {
            $input['order_process_id'] = $input['order_process_course_id'];
        }

        //逻辑调整传入的id实际为员工工单id
        $orderProcessCourseId = $input['order_process_id'];
        $orderProcessCourseRow = OrderProcessCourse::where(['id' => $orderProcessCourseId])->first()->toArray();

        ////判断对应工序下是否有多个员工-- 20180228调整 一个员工也不需要限制完成数量&完成数量从分批提交的数中获取

        //校验参数
        $rules = [
            'order_process_id' => 'required',
        ];
        $messages = [
            'order_process_id.required' => '缺少工单id',
        ];
        $this->validateRequestParameters($input, $rules, true, $messages);


        //获取对应工单工序表信息
        $orderProcessInfo = OrderProcess::where('id', $orderProcessCourseRow['order_process_id'])->first()->toArray();
        $curOrderProcessId = $orderProcessInfo['id'];
        //获取工单信息
        $orderInfo = Order::where('id', $orderProcessInfo['order_id'])->first()->toArray();
        $order_title = $orderInfo['order_title'];
        $foreignKey = intval($orderInfo['customer_order_id']);
        //获取工序名称
        //获取工序名称
        $processInfo = Process::getOneValueById($orderProcessInfo['process_type'], ['title','measurement_unit']);
        $processTitle = $processInfo['title'];
        $processMeasurementUnit = $processInfo['measurement_unit'];



        //如果上一部门没有完工，限制提交完工
        $orderProcessId = $orderProcessInfo['id'];
        //获取前一步骤所有工艺
        $preOrderProcessList = OrderType::getAllPrevOrderProcess($orderInfo['order_type'], $orderProcessInfo['process_type']);
        if ($preOrderProcessList) {
            $preOrderProcessList = $preOrderProcessList->toArray();
        } else {
            $preOrderProcessList = [];
        }

        $noCompleteProcessNum = OrderProcess::all()->whereIn('process_type', $preOrderProcessList)->whereIn('status', array(1, 2, 3, 101))->where('order_id', $orderProcessInfo['order_id'])->count();
        if ($noCompleteProcessNum) {
            return [
                'code' => 1,
                'message' => '请等待上道工序完工'
            ];
        }




        //修改员工工单工序状态
        $orderProcessCourseObj = OrderProcessCourse::where('id', $orderProcessCourseId)->first();
//        $orderProcessCourseObj->finish_number = $input['completed_number'];
        $orderProcessCourseObj->meter_counter = $input['meter_counter'];
        $orderProcessCourseObj->finish_number_piece = $input['finish_number_piece'];
//        $orderProcessCourseObj->waste_number = $input['waste_number'];
        $orderProcessCourseObj->status = 4;
        $orderProcessCourseObj->remark = $inputRemark;
        $orderProcessCourseObj->save();

        //修改工单列表关联表数据状态
        $type = 4;
        $relateId = $orderProcessCourseObj->id;
        $status = 4;
        OrderEngine::changeOrderListRelationStatus($type, $relateId, $status);


        //更新员工给管理员发的那条消息状态为2已完工(需原状态为1生产中)
        //$typeUserId = $orderProcessCourseObj->assign_id;
        $typeId = $orderProcessCourseId;
        //UserMessage::updateTypeStatusByTypeId(3, $typeId, $typeUserId, 2);
        //更新员工的消息为已完工
        $courseUid = $orderProcessCourseObj->uid;
        UserMessage::updateTypeStatusByTypeId(1, $typeId, $courseUid, 4);

        //已调整 zhuyujun 20181212
        //一个员工的工序单完工时给工序管理员和下单人发消息
//        $messageContent = '工单编号: ' . $orderInfo['order_title'];
//        $messageContent .= 'rnrn工序名称: ' . $processTitle;
//        $messageArr = [
//            'user_id' => $orderProcessCourseObj->uid,
//            'company_id' => $orderProcessCourseObj->company_id,
//            'customer_order_id' => $orderInfo['customer_order_id'],
//            'order_process_course_id' => $orderProcessCourseObj->id,
//            'order_create_id' => $orderInfo['uid'],
//            'order_admin_id' => $orderProcessInfo['uid'],
//            'content' => $messageContent,
//        ];
//        $this->sendMessageByType($messageArr, 1);

//        主题：工单任务已完工
//内容：工单号、合计完工数量

        $tmpOrderTitle = \App\Engine\Common::changeSnCode($orderInfo['order_title']);
        $messageContent = "工单号:{$tmpOrderTitle}rnrn";
        $messageContent.= "合计完工数量:{$orderProcessCourseObj['finish_number']}{$processMeasurementUnit}rnrn";

        $data = [
            'company_id' => $orderProcessInfo['company_id'],
            'privilege_id' => '',
            'form_user_id' => $userId,
            'to_user_id' => $orderProcessInfo['uid'],
            'foreign_key' => $foreignKey,
            'type' => 35,//纯展示
            'type_id' => $orderProcessInfo['id'],
            'title' => $orderInfo['order_title'],
            'content' => $messageContent,
            'theme' => '工单任务已完工',
        ];
        UserMessage::sendCustomerOrderMessage($data);


        //判断工单工序是否完成
        $noCompleteProcessCourseNum = OrderProcessCourse::where(['order_process_id' => $orderProcessInfo['id']])->where('status', '!=', 4)->count();
        if ($noCompleteProcessCourseNum == 0) {
            //工序完成时，统计工序总完成数量
            $processIsSum = Process::getOneValueById($orderProcessInfo['process_type'], 'is_sum');

            $orderProcessCourseList = OrderProcessCourse::where(['order_process_id' => $orderProcessInfo['id']])->get();
            $finishNum = 0;

            $finishUserNumList = [];
            foreach ($orderProcessCourseList as $orderProcessCourseRow) {
                $finishNum += $orderProcessCourseRow['finish_number'];
                if (!$processIsSum) {//不累加
                    $tmpUserInfo = DepartmentUser::getCurrentInfo($orderProcessCourseRow['uid'])->toArray();
                    $tmpPrivilegeId = $tmpUserInfo['privilege_id'];
                    if (isset($finishUserNumList[$tmpPrivilegeId])) {
                        $finishUserNumList[$tmpPrivilegeId]['finish_number'] += $orderProcessCourseRow['finish_number'];
                    } else {
                        $finishUserNumList[$tmpPrivilegeId]['finish_number'] = $orderProcessCourseRow['finish_number'];
                    }
                }
            }

            //不累加--未完工时取完成量最小的员工
            if (!empty($finishUserNumList)) {
                $finishMinNum = '';
                foreach ($finishUserNumList as $privilegeId => $finishUserNumRow) {
                    if ($finishMinNum === 0) {//如果有员工完成数量为0，
                        break;
                    }

                    if ($finishUserNumRow['finish_number'] < $finishMinNum || $finishMinNum === '') {//如果有员工完成数量更少，或者第一个员工的数据
                        $finishMinNum = $finishUserNumRow['finish_number'];
                    }
                }
                $finishNum = $finishMinNum;
            }

            //如果版的使用记录
            $orderProcessObj = OrderProcess::where(['id' => $curOrderProcessId])->first();
            $companyId = $orderProcessObj->company_id;
            $orderId = $orderProcessObj->order_id;

            //获取字段信息
            $processFieldList = Process::getFieldListByProcessId($orderProcessObj->process_type);
            foreach ($processFieldList as $processFieldRow) {
                $tmpFiledType = ProcessField::getFieldTypeByFieldName($processFieldRow['field_name'], $companyId);
                if ($tmpFiledType == 17) {//添加关联关系
                    $tmpFiledName = $processFieldRow['field_name'];



                    if ($orderProcessObj->$tmpFiledName && is_numeric($orderProcessObj->$tmpFiledName)) {
                        //逻辑调整后，用新方式获取版ID
                        $tmpCreateOrderPlateRow = \App\Eloquent\Ygt\CreateOrderPlate::where(['id' => $orderProcessObj->$tmpFiledName])->first();
                        if($tmpCreateOrderPlateRow){
                            $tmpCreateOrderPlateRowContent = json_decode(htmlspecialchars_decode($tmpCreateOrderPlateRow['content']), true);
                            if($tmpCreateOrderPlateRowContent['plate_id']){
                                //添加关联关系
                                $orderPlateObj = OrderPlate::firstOrNew(
                                    [
                                        'order_process_id'=>$orderProcessObj->id,
                                        'plate_id'=>$tmpCreateOrderPlateRowContent['plate_id'],
                                        'field_name'=>$tmpFiledName
                                    ]
                                );
                                $insertRow = [];
                                $insertRow['order_id'] = $orderId;
                                $insertRow['order_process_id'] = $orderProcessObj->id;
                                $insertRow['plate_id'] = $tmpCreateOrderPlateRowContent['plate_id'];
                                $insertRow['company_id'] = $companyId;
                                $insertRow['number'] = $finishNum;

                                $orderPlateObj->fill($insertRow);
                                $orderPlateObj->save();

                                //修改版的数据
                                $plateObj = Plate::where(['id' => $tmpCreateOrderPlateRowContent['plate_id']])->first();
                                if ($plateObj) {
                                    $plateObj->order_times = $plateObj->order_times + 1;
                                    $plateObj->finish_number = $plateObj->finish_number + $finishNum;
                                    $plateObj->last_time = time();
                                    $plateObj->save();
                                }
                            }
                        }

                    }
                }
            }


            $orderProcessObj = OrderProcess::where('id', $orderProcessInfo['id'])->first();
            $orderProcessObj->status = 4;
            $orderProcessObj->save();

            //修改工单列表关联表数据状态
            $type = 2;
            $relateId = $orderProcessObj->id;
            $status = 4;
            OrderEngine::changeOrderListRelationStatus($type, $relateId, $status);


            ////判断是否发信息给下一道工艺的员工
            //获取当前步骤所有工艺
            $curOrderProcessList = OrderType::getCurrentOrderProcess($orderInfo['order_type'], $orderProcessInfo['process_type'])->toArray();
            //判断当前步骤的工艺是否都已经完成
            $noCompleteProcessNum = OrderProcess::all()->whereIn('process_type', $curOrderProcessList)->where('status', '!=', 4)->where('order_id', $orderProcessInfo['order_id'])->count();
            if ($noCompleteProcessNum == 0) {
                $userRow = DepartmentUser::getCurrentInfo($orderInfo['uid'])->toArray();
                //推送消息
                //获取下一步骤所有工序
                $nextProcessList = OrderType::getAllNextOrderProcess($orderInfo['order_type'], $orderProcessInfo['process_type'])->toArray();
                if (!empty($nextProcessList)) {

                    ////流程调整后，不需要在订单完成后给下一个工序的相关人员发送消息
                    /*工序完工后给下一个工序的管理员和员工发送消息  -- 又要了。。*/
                    foreach ($nextProcessList as $tmpProcessId){
//                        内容：工单号、合计完工数量
                        //工序管理员
                        $tmpOrderProcessRow = \App\Eloquent\Ygt\OrderProcess::where(['order_id'=>$orderInfo['id'],'process_type'=>$tmpProcessId])->first();
                        $tmpOrderTitle = \App\Engine\Common::changeSnCode($orderInfo['order_title']);
                        $messageContent = "工单号:{$tmpOrderTitle}rnrn";
                        $messageContent.= "合计完工数量:{$tmpOrderProcessRow['completed_number']}{$processMeasurementUnit}rnrn";

                        $data = [
                            'company_id' => $companyId,
                            'privilege_id' => '',
                            'form_user_id' => $userId,
                            'to_user_id' => $tmpOrderProcessRow['uid'],
                            'foreign_key' => $foreignKey,
                            'type' => 35,//纯展示
                            'type_id' => $orderProcessInfo['id'],
                            'title' => $tmpOrderTitle,
                            'content' => $messageContent,
                            'theme' => '工单任务已完工',
                        ];
                        UserMessage::sendCustomerOrderMessage($data);

                        //员工
                        $tmpOrderProcessCourseList = \App\Eloquent\Ygt\OrderProcessCourse::where(['order_process_id'=>$tmpOrderProcessRow['id']])->get();
                        foreach ($tmpOrderProcessCourseList as $tmpOrderProcessCourseRow){
                            $data = [
                                'company_id' => $companyId,
                                'privilege_id' => '',
                                'form_user_id' => $userId,
                                'to_user_id' => $tmpOrderProcessCourseRow['uid'],
                                'foreign_key' => $foreignKey,
                                'type' => 35,//纯展示
                                'type_id' => $orderProcessInfo['id'],
                                'title' => $tmpOrderTitle,
                                'content' => $messageContent,
                                'theme' => '工单任务已完工',
                            ];
                            UserMessage::sendCustomerOrderMessage($data);
                        }
                    }
                }

                ////如果当前阶段工序都已经完成且无下一阶段的工序，主工单状态设置为完成 -- 逻辑调整，所有工单都完成后主订单才算完成20180209
                //获取未完工的工序工单的数量
                $where = [
                    ['order_id', '=', $orderProcessInfo['order_id']],
                    ['status', '!=', 4],
                ];
                $orderProcessNoCompleteNum = OrderProcess::where($where)->get()->count();

                if ($orderProcessNoCompleteNum == 0) {

                    $orderObj = Order::where('id', $orderProcessInfo['order_id'])->first();
                    $orderObj->status = 3;
                    $orderObj->save();
                    $orderId = $orderObj->id;

                    //修改工单列表关联表数据状态
                    $type = 1;
                    $relateId = $orderObj->id;
                    $status = 3;
                    OrderEngine::changeOrderListRelationStatus($type, $relateId, $status);

                    //修改订单状态
                    $customerOrderId = $orderObj->customer_order_id;
                    \App\Engine\OrderEngine::changeCustomerOrderStatus($customerOrderId, 5);//修改状态为已完工


                    //工单完成后给相关角色发送报表
//                    //获取报表列表
//                    $companyId = $orderInfo['company_id'];
//                    $orderReportTypeList = OrderReportType::where(['company_id' => $companyId])->get();
//                    foreach ($orderReportTypeList as $orderReportTypeRow) {
//                        $orderReportTypeId = $orderReportTypeRow['id'];
//                        //存入工单报表关联表
//                        $orderReport = OrderReport::firstOrNew(['id' => '']);
//                        $orderReportRow = [
//                            'order_id' => $orderInfo['id'],
//                            'order_report_type_id' => $orderReportTypeId,
//                            'company_id' => $companyId
//                        ];
//                        $orderReport->fill($orderReportRow);
//                        $orderReport->save();
//                        $orderReportId = $orderReport->id;
//
//                        //发送消息给相关人员
//                        $privilegeIds = $orderReportTypeRow['send_user'];
//                        $privilegeIdList = explode(',', $privilegeIds);
//                        foreach ($privilegeIdList as $privilegeId) {
//                            if ($privilegeId) {
//                                $data = [
//                                    'company_id' => $companyId, 'privilege_id' => $privilegeId,
//                                    'form_user_id' => $orderProcessCourseRow['uid'], 'to_user_id' => '',
//                                    'foreign_key' => $foreignKey,
//                                    'type' => 11, 'type_id' => $orderReportId,
//                                    'title' => $orderInfo['order_title'], 'content' => '有个工单完工了，请查看详情'
//                                ];
//                                UserMessage::sendCustomerOrderMessage($data);
//                            }
//                        }
//                    }


                }
            }
        }


        if (!empty($input['material_list'])) {//如果没有取材料不走出入库方法
            Stock::OrderProcessCourseStockIn($orderProcessCourseId);
        }
        return '确认完工';
    }
    //在该类中涉及到发消息,建议都放入到该方法内
    //$arr 不同type中内容不一样,自行设置
    //type==1 员工完工时给下单人和工序管理员发消息
    private function sendMessageByType($arr, $type = 1)
    {
        switch ($type) {
            case 1:
                //员工完工时给下单人和工序管理员发消息
                //    $arr                = [
                //        'user_id'=>'当前登录人的id',
                //        'company_id'=>'当前登录人的厂id',
                //        'customer_order_id'=>'WorkFlowId',
                //        'order_process_course_id'=>'供应商id',
                //        'order_create_id'=>'下单人的用户id',
                //        'order_admin_id'=>'工序管理员的用户id',
                //        'content'=>'消息的内容',
                //    ];
                $userId = $arr['user_id'];
                $companyId = $arr['company_id'];
                $foreignKey = $arr['customer_order_id'];
                $typeId = $arr['order_process_course_id'];
                $messageContent = $arr['content'];
                $title = '工序工单完工';
                //30=>'工单完工',///员工完工时给工序管理员发消息
                $messageData = [
                    'company_id' => $companyId,
                    'privilege_id' => 0,
                    'form_user_id' => $userId,
                    'to_user_id' => $arr['order_admin_id'],
                    'foreign_key' => $foreignKey,
                    'type' => 30,
                    'type_id' => $typeId,
                    'title' => $title,
                    'content' => $messageContent,
                    'type_status' => 1,
                ];
                \App\Eloquent\Ygt\UserMessage::sendCustomerOrderMessage($messageData);
                //31=>'工单完工',///员工完工时给下单人发消息
                $messageData = [
                    'company_id' => $companyId,
                    'privilege_id' => 0,
                    'form_user_id' => $userId,
                    'to_user_id' => $arr['order_create_id'],
                    'foreign_key' => $foreignKey,
                    'type' => 31,
                    'type_id' => $typeId,
                    'title' => $title,
                    'content' => $messageContent,
                    'type_status' => 1,
                ];
                \App\Eloquent\Ygt\UserMessage::sendCustomerOrderMessage($messageData);
                break;
            case 38:
                //38=>'生产派单',//下单人生产派单时给发货员发消息---2018-8-28新增
                //下单派发工单后，发货员也需要像财务一样收到工单消息，消息详情内容：工艺名称、品名、成品规格、成品重量、下单数量、交货日期和收货信息
                $formUserId     = $arr['form_user_id'];
                $companyId      = $arr['company_id'];
                $foreignKey     = $arr['foreign_key'];
                $typeId         = $arr['type_id'];
                $messageContent = $arr['content'];
                $title          = $arr['title'];
                $typeStatus     = $arr['type_status'];
                $privilegeList = \App\Engine\OrderEngine::getPrivilegeByNode($companyId, 12);
                foreach ($privilegeList as $privilegeId) {
                    $data = [
                        'company_id' => $companyId,
                        'privilege_id' => $privilegeId,
                        'form_user_id' => $formUserId,
                        'to_user_id' => '',
                        'foreign_key' => $foreignKey,
                        'type' => 38,
                        'type_id' => $typeId,
                        'title' => $title,
                        'content' => $messageContent,
                        'type_status' =>$typeStatus,
                    ];
                    \App\Eloquent\Ygt\UserMessage::sendCustomerOrderMessage($data);
                }
                break;
            default:
        }
    }

    //确认完工详情页
    public function completeOrderDetail(Request $request)
    {
        //获取传入数据
        $input = $request->all();
        $input['order_process_id'] = isset($input['order_process_id']) ? $input['order_process_id'] : '';//工序工单id
        $input['order_process_course_id'] = isset($input['order_process_course_id']) ? $input['order_process_course_id'] : '';//员工id

        $userId = Func::getHeaderValueByName('userid');
        $userInfo = DepartmentUser::getCurrentInfo($userId)->toArray();
        $companyId = $userInfo['company_id'];

        //逻辑调整传入的id实际为员工工单id
        if ($input['order_process_course_id']) {
            $orderProcessCourseId = $input['order_process_course_id'];
            $orderProcessCourseRow = OrderProcessCourse::where(['id' => $orderProcessCourseId])->first()->toArray();
            $orderProcessId = $orderProcessCourseRow['order_process_id'];

            $input['order_process_id'] = $orderProcessCourseId;
        } else {
            $orderProcessId = $input['order_process_id'];
        }


        //校验参数
        $rules = [
            'order_process_id' => 'required',
        ];
        $messages = [
            'order_process_id.required' => '缺少工单id',
        ];
        $this->validateRequestParameters($input, $rules, true, $messages);

        //获取对应工单工序表信息
        $orderProcessInfo = OrderProcess::where('id', $orderProcessId)->first()->toArray();
        //获取工单信息
        $orderInfo = Order::where('id', $orderProcessInfo['order_id'])->first()->toArray();
        //获取工序名称
        $processTitle = Process::getOneValueById($orderProcessInfo['process_type'], 'title');

        $processFieldList = Process::getFieldListByProcessId($orderProcessInfo['process_type']);

        $apeList = [];

        //追加工单基础信息
        $processOrderTypeId = $orderProcessInfo['ordertype_process_id'];//工序工单
        $privilegeId = $userInfo['privilege_id'];//角色id
        $baseFieldList = PermissionEngine::getBasePrivilegeFieldsByProcessOrderType($processOrderTypeId, $privilegeId);

        foreach ($baseFieldList as $baseFieldRow) {
            $showTitle = '';
            if (isset($orderInfo[$baseFieldRow['field_name']])) {
                $showTitle = $orderInfo[$baseFieldRow['field_name']];//默认展示字段的内容
            }

            $tmpFiledType = \App\Eloquent\Ygt\OrderFieldCompany::getFieldTypeByFieldName($baseFieldRow['field_name'], $companyId);
            $showTitle = OrderEngine::getOrderFiledValueTrue($orderInfo[$baseFieldRow['field_name']], $tmpFiledType);

            $apeList[] = [
                '$leftLabelValue' => $baseFieldRow['title'],
                '$rightLabelValue' => $showTitle,
            ];

        }


        foreach ($processFieldList as $processFieldRow) {
            if ($processFieldRow['field_name'] == 'remark') {//备注另外处理
                continue;
            }

            //通过字段类型不同处理
            //获取字段对应的类型1=>'文本',2=>'文本域',3=>'下拉框-跳界面',4=>'跳材料',5=>'有单位',6=>'开关',7=>'时间'
            $tmpFiledType = ProcessField::getFieldTypeByFieldName($processFieldRow['field_name'], $companyId);
            $showTitle = $orderProcessInfo[$processFieldRow['field_name']];//默认展示字段的内容

            if ($tmpFiledType == 4) {//材料选择暂时不显示在
                continue;
            }

            $showTitle = OrderEngine::getOrderFiledValueTrue($orderProcessInfo[$processFieldRow['field_name']], $tmpFiledType);

            if ($input['order_process_course_id']) {//员工查看分配自己
                if ($processFieldRow['field_name'] == 'completed_number') {//需完成数量，员工使用被分配的数量
                    $showTitle = $orderProcessCourseRow['total_number'];
                }
            }

            $apeList[] = [
                '$leftLabelValue' => $processFieldRow['title'],
                '$rightLabelValue' => $showTitle,
            ];
        }


        //添加计件工资
        if (isset($orderProcessId, $privilegeId, $orderProcessCourseId)) {
            $pieceWage = \App\Engine\OrderEngine::getEmployeePieceWage($orderProcessId, $privilegeId, $orderProcessCourseId);
            $apeList[] = [
                '$leftLabelValue' => '计件工资',
                '$rightLabelValue' => $pieceWage ? $pieceWage : '未设置',
            ];
        }



        //材料领取
        $apeList1 = [];
        if (!$input['order_process_course_id']) {//管理员或其他角色进入，查看工序工单整体情况
            //获取所有员工的领取材料情况
            $orderProcessCourseList = OrderProcessCourse::where(['order_process_id' => $orderProcessInfo['id']])->get()->toArray();
            $orderPorcessCourseIds = [];
            $finishNum = 0;//已完成数量
            foreach ($orderProcessCourseList as $orderProcessCourseRow) {
                $orderPorcessCourseIds[] = $orderProcessCourseRow['id'];
                $finishNum += $orderProcessCourseRow['finish_number'];
            }

            $orderMaterialArr = OrderMaterialCourse::where(['process_type' => $orderProcessInfo['process_type']])->whereIn('order_process_course_id', $orderPorcessCourseIds)->get()->toArray();

            $orderMaterialListTmp = [];
            foreach ($orderMaterialArr as $orderMaterialRow) {
                if (isset($orderMaterialListTmp[$orderMaterialRow['material_id']])) {
                    $orderMaterialListTmp[$orderMaterialRow['material_id']]['receive_number'] += $orderMaterialRow['receive_number'];
                    $orderMaterialListTmp[$orderMaterialRow['material_id']]['residual_number'] += $orderMaterialRow['residual_number'];
                    $orderMaterialListTmp[$orderMaterialRow['material_id']]['scrap_number'] += $orderMaterialRow['scrap_number'];
                } else {
                    $orderMaterialListTmp[$orderMaterialRow['material_id']] = $orderMaterialRow;
                }
            }

            $orderMaterialList = [];
            foreach ($orderMaterialListTmp as $orderMaterialRow) {
                $orderMaterialList[] = $orderMaterialRow;
            }
        } else {//员工进入,查看单员工情况
            $orderMaterialList = OrderMaterialCourse::where(['order_process_course_id' => $orderProcessCourseId, 'process_type' => $orderProcessInfo['process_type']])->get()->toArray();
            $finishNum = $orderProcessCourseRow['finish_number'];//已完成数量
        }

        foreach ($orderMaterialList as $orderMaterialRow) {
            //获取材料信息
            $materialRow = ProductEngine::getProductInfo($orderMaterialRow['material_id']);
            //废品率
            $userNum = $orderMaterialRow['receive_number'] - $orderMaterialRow['residual_number'];
            if ($userNum) {
                $rejectRate = (round($orderMaterialRow['scrap_number'] / $userNum * 100, 4)) . '%';
            } else {
                $rejectRate = 0;
            }


            $apeList1[] = [
                '$fistVlaue0' => $orderMaterialRow['receive_number'],
                '$fistVlaue1' => $orderMaterialRow['residual_number'],
                '$fistVlaue2' => $orderMaterialRow['scrap_number'],
                '$fitsTitleVlaue0' => '数量',
                '$fitsTitleVlaue1' => '数量',
                '$fitsTitleVlaue2' => '数量',
                '$secondTitleValue0' => '单位',
                '$secondTitleValue1' => '单位',
                '$secondTitleValue2' => '单位',
                '$secondValue0' => $materialRow['unit'],
                '$secondValue1' => $materialRow['unit'],
                '$secondValue2' => $materialRow['unit'],
                '$statusValue0' => '已领取',
                '$statusValue1' => '余品数',
                '$statusValue2' => '废品数',
                '$lose' => $rejectRate,
                '$productName' => $materialRow['product_name']
            ];
        }


        //获取工艺单位
        $curProcessRow = \App\Eloquent\Ygt\Process::getInfo(['id' => $orderProcessInfo['process_type']])->toArray();
        if($curProcessRow['measurement_unit']){
            $curProcessMeasurementUnit = $curProcessRow['measurement_unit'];
        }else{
            $curProcessMeasurementUnit = '';
        }

        //添加完成数量
        if($input['order_process_course_id']){
            if($finishNum){
                $apeList[] = [
                    '$leftLabelValue' => '完成数量',
                    '$rightLabelValue' => $finishNum.$curProcessMeasurementUnit,
                ];
            }
        }

        //获取员工的角色id，判断是否需要输入件数 20180110
        $orderProcessCourseId = $input['order_process_course_id'];
        $orderProcessCourseRow = OrderProcessCourse::where(['id' => $orderProcessCourseId])->first()->toArray();
        $personnelId = $orderProcessCourseRow['uid'];
        $personnelRow = DepartmentUser::getCurrentInfo($personnelId)->toArray();
        $personnelPrivilegeId = $personnelRow['privilege_id'];


        $ableFinishedProduct = 0;
        $tmpAbleFinishedProduct = OrderEngine::getPrivilegeFinishedProduct($personnelPrivilegeId, $orderProcessInfo['ordertype_process_id']);
        if ($tmpAbleFinishedProduct) { //格式统一 1--可以 0--禁止
            $ableFinishedProduct = 1;
        }



        $returnApe = [
            'pageID' => 2,
            'data' => [
                '$commentValue' => $orderProcessInfo['remark'],
                '$titleLabelValue' => $processTitle,
                '$numberOfDoneValue' => $finishNum,
                '$list' => $apeList,
                '$list1' => $apeList1
            ],
            'submit_material_id' => $orderProcessInfo['id'],//提交用料时所需传的ID
            'able_submit_material' => 1,//是否可以提交用料
            'able_finished_product' => $ableFinishedProduct,//是否有成品入库按钮 1-有 0-无
        ];

        return $returnApe;
    }

    //工序信息获取统一接口
    public function getProcessDetail(Request $request)
    {
        //获取传入数据
        $input = $request->all();
        $input['process_id'] = isset($input['process_id']) ? $input['process_id'] : '';//工单工序类型id
        $input['ordertype_process_id'] = isset($input['ordertype_process_id']) ? $input['ordertype_process_id'] : 0;//工单工序类型id
        $input['order_id'] = isset($input['order_id']) ? $input['order_id'] : '';//工单id 测试数据1
        $input['copy_order_id'] = isset($input['copy_order_id']) ? $input['copy_order_id'] : '';//被复制的工单id 测试数据
        $pre_order_id = isset($input['pre_order_id']) ? $input['pre_order_id'] : '';//草稿箱工单id 测试数据

        $curOrderProcessRow = OrderProcessPre::where(['order_id' => $input['order_id'], 'process_type' => $input['process_id']])->first();
        if ($curOrderProcessRow) {
            $curOrderProcessRow = $curOrderProcessRow->toArray();
        } else {
            $curOrderProcessRow = [];
        }

        if ($pre_order_id) {
            $curOrderProcessRow = OrderProcessPre::where(['order_id' => $pre_order_id, 'process_type' => $input['process_id']])->first();
            if ($curOrderProcessRow) {
                $curOrderProcessRow = $curOrderProcessRow->toArray();
            }
            $input['order_id'] = $pre_order_id;
        } elseif ($input['copy_order_id']) {//如果传入复制工单id
            if (OrderProcess::where(['order_id' => $input['copy_order_id'], 'process_type' => $input['process_id']])->first()) {
                $curOrderProcessRow = OrderProcess::where(['order_id' => $input['copy_order_id'], 'process_type' => $input['process_id']])->first()->toArray();
            } else {
                $curOrderProcessRow = [];
            }
        }


        //获取工单信息
        $orderInfo = OrderPre::where(['id' => $input['order_id']])->first()->toArray();
        $orderType = $orderInfo['order_type'];

        //通过工序id，获取对应的字段
        $processFieldList = Process::getFieldListByProcessId($input['process_id']);
        //如果是第一道工序，添加字段需完成数量----功能调整取消这一段
//        $processFirstList = OrderType::getFirstProcessBag($orderInfo['order_type'])->toArray();
//        if (in_array(d['process_id'], $processFirstList)){
//            $processFieldList[]=[
//                'id'=>0, 'field_name'=>'completed_number', 'title'=>'需完成数量', 'field_type'=>1, 'text_type'=>1,
//                'placeholder'=>'请填写', 'is_must'=>1, 'relation_id'=>0,'field_unit'=>[],'data'=>[]
//            ];
//        }

        //获取工序信息
        $processTitle = Process::getOneValueById($input['process_id'], 'title');

        //是否为工艺上最后一个工序
        $orderTypeObj = new OrderType();
        if ($input['ordertype_process_id']) {//新旧兼容
            $nextOrderTypeProcessRow = $orderTypeObj->getNextStep($input['ordertype_process_id']);//获取下一个工序
            $nextProcessId = $nextOrderTypeProcessRow[0]['process_id'];
        } else {
            $nextProcessId = $orderTypeObj->getNextOneProcessId($orderType, $input['process_id']);//获取下一个工序
        }


        $buttonTitle = '';
        if ($nextProcessId) {
            $buttonTitle = '下一步';//按钮显示文字
        } else {
            $buttonTitle = '保存';//按钮显示文字
        }

        //获取工艺数目
        $curProcessNum = OrderType::getOrderTypeProcessNumber($orderType, $input['process_id']);

        $processNum = OrderType::getAllOrderTypeProcess($orderType)->count();

        //添加默认值
        if (!empty($curOrderProcessRow)) {
            foreach ($processFieldList as $key => $row) {
                if (isset($curOrderProcessRow[$row['field_name']]) && $curOrderProcessRow[$row['field_name']]) {
                    if ($row['field_type'] == 3) {//选择 处理
                        $selectId = $this->getSidByTitle($curOrderProcessRow[$row['field_name']], $row['data']);
                        $processFieldList[$key]['default_select_id'] = $selectId;
                        $processFieldList[$key]['default_value'] = $curOrderProcessRow[$row['field_name']];
                    } elseif ($row['field_type'] == 5) {//填写+单位选择 处理
                        $oldRow = $curOrderProcessRow[$row['field_name']];
                        $oldRowArr = explode(',', $oldRow);
                        if (count($oldRowArr) > 1) {//异常数据处理
                            $defaultValue = $oldRowArr[0];
                            $oldUnitTitle = $oldRowArr[1];
                            $oldUnitId = $this->getUnitIdByTitle($oldUnitTitle, $row['field_unit']);
                            if (!$oldUnitId) {
                                if (count($row['field_unit'])) {
                                    $oldUnitId = $row['field_unit'][0]['id'];
                                    $oldUnitTitle = $row['field_unit'][0]['title'];
                                } else {
                                    $oldUnitId = 0;
                                    $oldUnitTitle = '';
                                }
                            }

                            $processFieldList[$key]['default_value'] = $defaultValue;
                            $processFieldList[$key]['default_unit_id'] = $oldUnitId;
                            $processFieldList[$key]['default_unit_title'] = $oldUnitTitle;
                        }
                    } elseif ($row['field_type'] == 4) {//选择材料页面 zq
                        $materialIdListStr = $curOrderProcessRow[$row['field_name']];
                        $materialIdList = explode(',', $materialIdListStr);

                        $materialList = [];
                        //获取优选采购的材料id
                        $recommendMaterialIdArr = OrderMaterialPurchaseMark::where('order_pre_id','=',$orderInfo['id'])->where('is_purchase','=',1)->pluck('material_id')->toArray();
                        foreach ($materialIdList as $materialId) {
                            //考虑集合材料的问题
                            if(strstr($materialId,'A')){
                                $tmpAssemblageMaterialId = str_replace('A','',$materialId);
                                $materialRow = \App\Eloquent\Ygt\AssemblageMaterial::withTrashed()->where(['id'=>$tmpAssemblageMaterialId])->first();

                            }else{
                                $materialRow = ProductEngine::getProductInfo($materialId);
                            }


                            if ($materialRow) {//过滤异常情况
                                //增加材料图片地址 20180719 zhuyujun
                                //追加材料图片地址
                                $materialRow['img_url'] = '';
                                if ($materialRow['img_id']) {
                                    $materialRow['img_url'] = \App\Eloquent\Ygt\ImgUpload::getImgUrlById($materialRow['img_id']);
                                }


                                $materialRow->toArray();


                                //处理价格问题
                                $priceColor = '#000000';

                                //再来一单
                                if($input['copy_order_id']){
                                    //上次的价格
                                    $tmpPreMaterialPrice = 0;
                                    $tmpOrderMaterialRow = \App\Eloquent\Ygt\OrderMaterial::where(['order_id'=>$input['copy_order_id'],'material_id'=>$materialId])->first();
                                    if($tmpOrderMaterialRow){
                                        $tmpPreMaterialPrice = $tmpOrderMaterialRow['price'];
                                    }

                                    //现在的价格
                                    $tmpCurMaterialPrice = \App\Engine\Material::getMaterialPrice($materialId);

                                    if($tmpPreMaterialPrice && $tmpCurMaterialPrice){//如果没有值不做比较
                                        //价格降了（绿色）
                                        if($tmpPreMaterialPrice > $tmpCurMaterialPrice){
                                            $priceColor = "#7CFC00";
                                        }

                                        //价格涨了（红色）
                                        if($tmpPreMaterialPrice < $tmpCurMaterialPrice){
                                            $priceColor = "#EE3B3B";
                                        }
                                    }
                                }

                                //订单转工单
                                //获取订单对应的工单(最近的)
                                if($input['order_id']){
                                    $tmpOrderRow = \App\Eloquent\Ygt\Order::where(['id'=>$input['order_id']])->orderBy('id','desc')->first();
                                    $tmpCustomerOrderId = $tmpOrderRow['customer_order_id'];

                                    $tmpWhere = [];
                                    $tmpWhere[] = ['customer_order_id','=',$tmpCustomerOrderId];
                                    $tmpWhere[] = ['id','!=',$input['order_id']];//前一个工单
                                    $tmpOrderRow = \App\Eloquent\Ygt\Order::where($tmpWhere)->orderBy('id','desc')->first();
                                    if($tmpOrderRow){
                                        //上次的价格
                                        $tmpPreMaterialPrice = 0;
                                        $tmpOrderMaterialRow = \App\Eloquent\Ygt\OrderMaterial::where(['order_id'=>$tmpOrderRow['id'],'material_id'=>$materialId])->first();
                                        if($tmpOrderMaterialRow){
                                            $tmpPreMaterialPrice = $tmpOrderMaterialRow['price'];
                                        }

                                        //现在的价格
                                        $tmpCurMaterialPrice = \App\Engine\Material::getMaterialPrice($materialId);

                                        if($tmpPreMaterialPrice && $tmpCurMaterialPrice){//如果没有值不做比较
                                            //价格降了（绿色）
                                            if($tmpPreMaterialPrice > $tmpCurMaterialPrice){
                                                $priceColor = "#7CFC00";
                                            }

                                            //价格涨了（红色）
                                            if($tmpPreMaterialPrice < $tmpCurMaterialPrice){
                                                $priceColor = "#EE3B3B";
                                            }
                                        }

                                    }
                                }

                                if(in_array($materialId,$recommendMaterialIdArr)){
                                    $materialRow['is_purchase'] = 1;
                                }
                                else{
                                    $materialRow['is_purchase'] = 0;
                                }


                                $materialList[] = [
                                    'id' => $materialId,
                                    'product_no' => $materialRow['product_no'],
                                    'product_name' => $materialRow['product_name'],
                                    'image_path' => $materialRow['img_url'],
                                    'price_color' => $priceColor,
                                    'is_purchase' => $materialRow['is_purchase'],
                                ];
                            }

                        }
                        $processFieldList[$key]['default_product_list'] = $materialList;
                    } elseif ($row['field_type'] == 17) {//版 处理
//                        $selectId = $curOrderProcessRow[$row['field_name']];
//                        $processFieldList[$key]['default_select_id'] = $selectId;
//                        $plateRow = PlateEngine::getPlateInfo($selectId);
//
//                        if ($plateRow) {
////                            $tmpObj = \App\Eloquent\Ygt\BuyersProduct::where(['id'=>$plateRow['plate_name']])->first();
////                            if($tmpObj){
////                                $showTitle = $tmpObj['name'];
////                            }else{
////                                $showTitle = $plateRow['plate_name'];
////                            }
//                            $showTitle = $plateRow['plate_no'];
//                        } else {
//                            $showTitle = $curOrderProcessRow[$row['field_name']];
//                        }
//
//                        $processFieldList[$key]['default_value'] = $showTitle;

                        //新的版数据
                        $tmpCreateOrderPlateRow = \App\Eloquent\Ygt\CreateOrderPlate::where(['id'=>$curOrderProcessRow[$row['field_name']]])->first();
                        $plateInfo = json_decode(htmlspecialchars_decode($tmpCreateOrderPlateRow['content']), true);
                        if(empty($plateInfo)){
                            $plateInfo = null;
                        }

                        $processFieldList[$key]['default_value'] = '';
                        $processFieldList[$key]['default_plate_list'] = $plateInfo;

                    } elseif ($row['field_type'] == 18) {//客户 处理
                        $selectId = $curOrderProcessRow[$row['field_name']];
                        $processFieldList[$key]['default_select_id'] = $selectId;

                        $customerTitle = CustomerEngine::getNameById($selectId);
                        if ($customerTitle) {
                            $showTitle = $customerTitle;
                        } else {
                            $showTitle = $curOrderProcessRow[$row['field_name']];
                        }
                        $processFieldList[$key]['default_value'] = $showTitle;
                    } elseif ($row['field_type'] == 19) {//单位展示
                        $baseId = $curOrderProcessRow[$row['field_name']];
                        $showTitle = Buyers::getNameById($baseId);
                        if (!$showTitle) {
                            $showTitle = $curOrderProcessRow[$row['field_name']];
                        }
                        $processFieldList[$key]['default_value'] = $showTitle;
                    } elseif ($row['field_type'] == 22) {//半成品展示


                        $tmpCreateOrderProcessProductRow = \App\Eloquent\Ygt\CreateOrderProcessProduct::where(['id'=>$curOrderProcessRow[$row['field_name']]])->first();
                        $processProductInfo = json_decode(htmlspecialchars_decode($tmpCreateOrderProcessProductRow['content']), true);
                        if(empty($processProductInfo)){
                            $processProductInfo = null;
                        }

                        $processFieldList[$key]['default_value'] = '';
                        $processFieldList[$key]['default_process_product_list'] = $processProductInfo;


                    }
                    else {
                        $processFieldList[$key]['default_value'] = $curOrderProcessRow[$row['field_name']];
                    }


                }
            }
        }

        //追加再基础信息中填写的客户id
        $customerId = '';
        if (isset($orderInfo['customer_name']) && $orderInfo['customer_name'] && $orderInfo['customer_name'] != '(null)') {
            $customerId = $orderInfo['customer_name'];
        }

        //追加再基础信息中填写的品名id
        $plateNameId = '';
        if (isset($orderInfo['product_name']) && $orderInfo['product_name'] && $orderInfo['product_name'] != '(null)') {
            $plateNameId = $orderInfo['product_name'];
        }

        $return = [];
        $return['customer_id'] = $customerId;//基础信息的客户ID
        $return['plate_name_id'] = $plateNameId;//基础信息的品名ID
        $return['process_title'] = $processTitle;//工序名称
        $return['process_field_list'] = $processFieldList;//工序字段
        $return['button_title'] = $buttonTitle;//按钮显示文字
        $return['create_order_title'] = '创建工单（' . ($curProcessNum + 1) . '/' . ($processNum + 1) . '）';//按钮显示文字

        return $return;
    }

    //工序提交统一接口
    public function processSubmit(Request $request)
    {
        //获取传入数据
        $input = $request->all();
        $input['process_id'] = isset($input['process_id']) ? $input['process_id'] : '';//工单工序类型
        $input['ordertype_process_id'] = isset($input['ordertype_process_id']) ? $input['ordertype_process_id'] : 0;//工单工序类型关联id
        $input['order_id'] = isset($input['order_id']) ? $input['order_id'] : '';//工单-id
        $input['is_draft'] = isset($input['is_draft']) ? $input['is_draft'] : 0;//是否存入草稿箱，是的话不校验数据

        //验证字段是必填还是选填 by zzy
        if (!$input['is_draft']) {
            $processFieldList = Process::getFieldListByProcessId($input['process_id']);
            //如果是第一个工序，添加字段‘需完成数量’--功能调整取消这一段
//            $orderInfo = OrderPre::where(['id' => $input['order_id']])->first()->toArray();
//            $processFirstList = OrderType::getFirstProcessBag($orderInfo['order_type'])->toArray();
//            if (in_array($input['process_id'], $processFirstList)){
//                $processFieldList[]=[
//                    'id'=>0, 'field_name'=>'completed_number', 'title'=>'需完成数量', 'field_type'=>1, 'text_type'=>1,
//                    'placeholder'=>'请填写', 'is_must'=>1, 'relation_id'=>0,'field_unit'=>[],'data'=>[]
//                ];
//            }

            $processFieldRules = [];
            $processFieldMessage = [];
            foreach ($processFieldList as $key => $val) {
                $isMust = $val['is_must'];
                if ($isMust == 1) {
                    $rulesName = 'required';
                    $fieldName = $val['field_name'];
                    $fieldTitle = $val['title'];
                    $fieldMsg = $fieldName . '.' . $rulesName;
                    $processFieldRules[$fieldName] = $rulesName;
                    $processFieldMessage[$fieldMsg] = $fieldTitle . '必填';

                    $inputValue = $input[$fieldName];
                    if (empty($inputValue)) {
                        xThrow(ERR_PARAMETER, $fieldTitle . '必填');
                    }
                }
            }
        }
        //$this->validateRequestParameters($input, $processFieldRules, true, $processFieldMessage);

        //获取用户id
        $userId = Func::getHeaderValueByName('userid');
        $userInfo = DepartmentUser::getCurrentInfo($userId)->toArray();
        $companyId = isset($userInfo['company_id']) ? $userInfo['company_id'] : '';

        //获取工序所包含的字段
//        $processFieldList = Process::getFieldArrByProcessId($input['process_id']);
        $processFieldList = Process::getFieldListByProcessId($input['process_id']);

        //数据入库
        //存入印刷工序提交的数据
        $orderProcessPreRow = OrderProcessPre::firstOrNew(['order_id' => $input['order_id'], 'process_type' => $input['process_id']]);

        $insertRow = [
            'order_id' => $input['order_id'],//关联的工单id
            'process_type' => $input['process_id'],//工序类型
            'ordertype_process_id' => $input['ordertype_process_id'],//工序工单类型关联id
            'company_id' => $companyId,
        ];


        //如果是第一道工序，添加字段需完成数量--功能调整,第一个工序需完成数量取产品的数量
        //调整为所有工序需完成数量都由工单产品数量挂钩

        $orderInfo = OrderPre::where(['id' => $input['order_id']])->first();
//        $processFirstList = OrderType::getFirstProcessBag($orderInfo['order_type'])->toArray();
//        if (in_array($input['process_id'], $processFirstList)) {
        //获取工单基础信息设置的数量
        $tmpArr = explode(',', $orderInfo['product_num']);
        $productNum = $tmpArr[0];
        if (!$productNum || !is_numeric($productNum)) {
            $productNum = 0;
        }
//        $insertRow['completed_number'] = $productNum;
//        }




        //如果是最后一道工序，工单创建完成
        //获取工单信息
        $orderInfo = OrderPre::where(['id' => $input['order_id']])->first()->toArray();
        $orderType = $orderInfo['order_type'];


        //版管理特殊处理
        foreach ($processFieldList as $processFieldRow) {
            $processField = $processFieldRow['field_name'];

            //版特殊处理
            if($processFieldRow['field_type'] == 17){
                //限制-版数量想加不能超过产品数量
                $tmpPlateBranch = json_decode(htmlspecialchars_decode($input[$processField]), true);
                $tmpPlateNumAll = 0;

                if(isset($tmpPlateBranch['branch']['colourplate'])){
                    foreach ($tmpPlateBranch['branch']['colourplate'] as $tmpRow){
                        $tmpPlateNumAll += $tmpRow['num'];
                    }
                }

                if($tmpPlateNumAll && ($tmpPlateNumAll > $orderInfo['product_num']) ){
                    return [
                        'code' => 1,
                        'message' => '版支总数量不能超过产品数量',
                    ];
                }


                $tmpObj = \App\Eloquent\Ygt\CreateOrderPlate::firstOrNew(['id'=>'']);
                $tmpInsertRow = [
                    'type' => 2,
                    'relate_id' => $input['order_id'],
                    'field_name' => $processField,
                    'content' => $input[$processField],
                ];


                $tmpObj->fill($tmpInsertRow);
                $tmpObj->save();
                $createOrderPlateId = $tmpObj->id;

                $insertRow[$processField] = $createOrderPlateId;
            }
            //材料类型 zq
            else if($processFieldRow['field_type'] == 4){
                $input = OrderEngine::handleInput($input,$processField,$processFieldRow['field_type'],'purchase_info');
                $insertRow[$processField] = $input[$processField];
            }elseif($processFieldRow['field_type'] == 22){
                $tmpObj = \App\Eloquent\Ygt\CreateOrderProcessProduct::firstOrNew(['id'=>'']);
                $tmpInsertRow = [
                    'type' => 2,
                    'relate_id' => $input['order_id'],
                    'field_name' => $processField,
                    'content' => $input[$processField],
                ];

                $tmpObj->fill($tmpInsertRow);
                $tmpObj->save();
                $createOrderProcessProductId = $tmpObj->id;

                $insertRow[$processField] = $createOrderProcessProductId;
            }
            else{
                $insertRow[$processField] = $input[$processField];
            }
    }

        $orderProcessPreRow->fill($insertRow);
        $orderProcessPreRow->save();

        $orderTypeObj = new OrderType();
        $nextProcessId = $orderTypeObj->getNextOneProcessId($orderType, $input['process_id']);//获取下一个工序
        if ($input['ordertype_process_id']) {//新旧兼容
            $nextOrderTypeProcessRow = $orderTypeObj->getNextStep($input['ordertype_process_id']);//获取下一个工序
            $nextProcessId = $nextOrderTypeProcessRow[0]['process_id'];
            $nextOrdertypeProcessId = $nextOrderTypeProcessRow[0]['id'];
        } else {
            $nextProcessId = $orderTypeObj->getNextOneProcessId($orderType, $input['process_id']);//获取下一个工序
            $nextOrdertypeProcessId = '';
        }


        //保存优先采购信息
        if(isset($input['purchase_info']) && !empty($input['purchase_info'])){
            //获取相关订单信息
            $customerOrderInfo = CustomerOrder::where('id','=',$orderInfo['customer_order_id'])->first()->toArray();
            $purchase_info = $input['purchase_info'];
            foreach($purchase_info as $val){
                OrderMaterialPurchaseMark::updateOrCreate(
                    [
                        'customer_order_pre_id'=>$customerOrderInfo['order_pre_id'],
                        'customer_order_id'=>$orderInfo['customer_order_id'],
                        'order_pre_id'=>$input['order_id'],
                        'material_id'=>$val['id']
                    ],
                    [
                        'is_purchase'=>$val['is_purchase'],
                    ]
                );
            }
        }

        if ($nextProcessId || $input['is_draft']) {//有下一步或者是退出保存操作
            if ($nextProcessId) {
                $return = [
                    'is_final' => 0, //是否为最后一道工序
                    'message' => '提交成功',//提示信息
                    'next_process_id' => $nextProcessId,//下一道工序的id
                    'next_ordertype_process_id' => $nextOrdertypeProcessId,//下一道工序的工序工单类型关联id
                ];
            } else {
                $return = [
                    'is_final' => 0, //是否为最后一道工序
                    'message' => '提交成功',//提示信息
                ];
            }
        } else {//提交生成正式工单
            $orderCreateRe = $this->orderCreate($input['order_id']);
            $orderId = $orderCreateRe['order_id'];

            $orderCreateRe['order_title'] = \App\Engine\Common::changeSnCode($orderCreateRe['order_title']);
            $orderTitle = $orderCreateRe['order_title'];

            $return = [
                'is_final' => 1,//是否为最后一道工序
                'message' => '创建成功',//提示信息
                'order_id' => $orderId,//创建成功的工单id
                'order_type' => $orderType,//创建成功的工单工序类型
                'order_title' => "【工单号：{$orderTitle}】",//创建成功的工单工序类型
            ];

            //更新所有相关优先采购记录的order_id zq
            OrderMaterialPurchaseMark::where('order_pre_id','=',$input['order_id'])
                ->whereNull('order_id')
                ->update(['order_id'=>$orderId]);
        }

        return $return;
    }
    

    //管理员工单详情
    public function getManagerOrderDetail(Request $request)
    {
        //获取传入数据
        $input = $request->all();
        $input['order_id'] = isset($input['order_id']) ? $input['order_id'] : '';//工单-id


        //获取工单信息
        $orderInfo = Order::where('id', $input['order_id'])->first()->toArray();
        //获取工序名称
//        $processTitle = Process::getOneValueById($orderProcessInfo['process_type'], 'title');
//        $processFieldList = Process::getFieldListByProcessId($orderProcessInfo['process_type']);

        //处理图片数据
        $imgIdList = explode(',', $orderInfo['production_case_diagram']);
        $exampleImg = '';
        foreach ($imgIdList as $imgId) {
            if (!trim($imgId)) {//过滤空格 图片id应该不会有0
                continue;
            }
            if (!$exampleImg) {//取第一张图作为示例图
                $exampleImg = ImgUpload::getImgUrlById($imgId);
            }
        }

        //获取工单对应的所有工序
        $orderProcessList = OrderType::getAllOrderTypeProcess($orderInfo['order_type'])->toArray();
        $blueColor = '#00AAEE';
        $greColor = '#B5B5B5';
        $androidBgBlue = 'bluecircle.png';
        $androidBgGrey = 'graycircle.png';

        $tabviewSource = [];//对应页面上纵向列表
        $tabviewSource[] = [
            'idName' => 27,
            '$littleTimeValue' => date('H:i', $orderInfo['created_at']),
            '$otherTimeValue' => date('Y-m-d', $orderInfo['created_at']),
            '$seeDetaileFunctionName' => '',
            '$departmentManageValue' => '已下单，待处理',
            '$userManageValue' => '',
            '$workMachineValue' => '',
            '$lookDetaileButtonHiden' => 1,
            '$userManageHiden' => 1,
            '$workMachineHiden' => 1,
            '$planTimeValue' => '',
            '$planTimeHiden' => 1
        ];//对应页面上纵向列表


        $list = [];//对应页面上横向列表
        $list[] = [
            '$statusValue' => '',
            '$departmentValue' => '待处理',
            '$leftHiden' => 1,
            '$rightHiden' => 0,
            '$statusHiden' => 1,
            '$departmentFontColor' => $blueColor,
            '$statusViewBG' => $blueColor,
            '$statusViewBorderColor' => $blueColor,
            '$androidBg' => $androidBgBlue
        ];//默认自带条目

        foreach ($orderProcessList as $processId) {
            //获取工序信息
//            if (!OrderProcess::where(['order_id' => $orderInfo['id'], 'process_type' => $processId])->first()) {
//                dd(['order_id' => $orderInfo['id'], 'process_type' => $processId]);
//            }
            if (!$orderProcessInfo = OrderProcess::where(['order_id' => $orderInfo['id'], 'process_type' => $processId])->first()) {
                continue;
            }

            $orderProcessInfo = OrderProcess::where(['order_id' => $orderInfo['id'], 'process_type' => $processId])->first()->toArray();


            $processTitle = Process::getOneValueById($orderProcessInfo['process_type'], 'title');
            $preProcessEstimatedTime = $orderProcessInfo['start_time'] + $orderProcessInfo['estimated_time_hour'] * 3600 + $orderProcessInfo['estimated_time_minute'] * 60;

            //是否显示预估时间
            if ($orderProcessInfo['status'] == 1 || $orderProcessInfo['status'] == 4) {
                $planTimeValue = '';
                $planTimeHiden = 1;
            } else {
                if ($preProcessEstimatedTime < 631152000) {//过滤1970的情况
                    $planTimeValue = '';
                } else {
                    $planTimeValue = '预计完成时间：' . date('Y年m月d日 H时', $preProcessEstimatedTime);
                }
                $planTimeHiden = 1;
            }

            //已完成状态可以查看
            $lookDetaileButtonHiden = 0;
            $buttontitle = '查看';
            $seeDetaileFunctionName = 'seeDetaileAction';

            ////判断下一个工序是否需要工序管理员分派
            ////如果该工序没有设置工序管理员&未分派
            $privilegeAssignmentIds = PermissionEngine::getStepActionPrivilegeIdsByOrderTypeProcess($orderInfo['order_type'], $processId, 3);//1:查看;2:可写;3:分配;4:提交;5:转发;
            if ($orderProcessInfo['uid']) {
                $userInfo = DepartmentUser::getCurrentInfo($orderProcessInfo['uid'])->toArray();
                $showUserName = $userInfo['truename'];
            } else {
                $showUserName = '';
            }

            if (!$privilegeAssignmentIds->count()) {//工序没有设置工序管理员
                //工单操作改为员工

                //没有配置工序管理员&员工还未分派工单
                $orderProcessCourse = OrderProcessCourse::where(['order_process_id' => $orderProcessInfo['id']])->get();
                if (!$orderProcessCourse->count()) {//表示未分派
                    $buttontitle = '分派';
                    $seeDetaileFunctionName = 'goSendAction';
                    $showUserName = '无';
                } else {
                    $userInfo = DepartmentUser::getCurrentInfo($orderProcessCourse->first()->uid)->toArray();
                    $showUserName = $userInfo['truename'];
                    if ($orderProcessCourse->count() > 1) {
                        $showUserName .= '等';
                    }
                }
            }

            if ($orderProcessInfo['status']) {//待接单状态不显示 调整--待接单状态也显示 20180305 18:30
                //获取对应用户信息
                //$userInfo = DepartmentUser::getInfo(['user_id' => $orderProcessInfo['uid']])->toArray();
                //统计完工数量

                //调整-预计完成时间调整为从员工工单获取
                $orderProcessCourseList = OrderProcessCourse::where(['order_process_id' => $orderProcessInfo['id']])->get();
                $finishNum = 0;

                $processId = $orderProcessInfo['process_type'];
                $where = ['id' => $processId];
                $process = Process::getInfo($where)->toArray();
                $processIsSum = $process['is_sum'];//工序数量是否累加0不累加1累加

                $finishUserNumList = [];
                foreach ($orderProcessCourseList as $orderProcessCourseRow) {

                    //设定的角色不进行统计数量到工序数量中
                    //过滤异常数据
                    if (!DepartmentUser::getCurrentInfo($orderProcessCourseRow['uid'])) {
                        continue;
                    }
                    $tmpUserInfo = DepartmentUser::getCurrentInfo($orderProcessCourseRow['uid'])->toArray();
                    $tmpPrivilegeId = $tmpUserInfo['privilege_id'];
                    if (OrderEngine::getProcessNumNoStatistics($tmpPrivilegeId)) {
                        continue;
                    }

                    $finishNum += $orderProcessCourseRow['finish_number'];
                    if (!$processIsSum) {//不累加
                        $tmpUserInfo = DepartmentUser::getCurrentInfo($orderProcessCourseRow['uid'])->toArray();
                        $tmpPrivilegeId = $tmpUserInfo['privilege_id'];

                        if (isset($finishUserNumList[$tmpPrivilegeId])) {
                            $finishUserNumList[$tmpPrivilegeId]['finish_number'] += $orderProcessCourseRow['finish_number'];
                        } else {
                            $finishUserNumList[$tmpPrivilegeId]['finish_number'] = $orderProcessCourseRow['finish_number'];
                        }
                    }
                }

                //不累加--未完工时取完成量最小的员工
                if (!empty($finishUserNumList)) {
                    $finishMinNum = '';
                    foreach ($finishUserNumList as $privilegeId => $finishUserNumRow) {
                        if ($finishMinNum === 0) {//如果有员工完成数量为0，
                            break;
                        }

                        if ($finishUserNumRow['finish_number'] < $finishMinNum || $finishMinNum === '') {//如果有员工完成数量更少，或者第一个员工的数据
                            $finishMinNum = $finishUserNumRow['finish_number'];
                        }
                    }
                    $finishNum = $finishMinNum;
                }


                $tabviewSource[] = [
                    'idName' => 27,
                    '$littleTimeValue' => date('H:i', $orderProcessInfo['updated_at']),
                    '$otherTimeValue' => date('Y-m-d', $orderProcessInfo['updated_at']),
                    '$departmentManageValue' => '[处理部门]' . $processTitle,
                    '$userManageValue' => '处理人:' . $showUserName,
                    '$workMachineValue' => '完成数量' . $finishNum,//操作机 =>03
                    '$seeDetaileFunctionName' => $seeDetaileFunctionName . $orderProcessInfo['id'],
                    '$lookDetaileButtonHiden' => $lookDetaileButtonHiden,
                    '$buttontitle' => $buttontitle,
                    '$userManageHiden' => 0,
                    '$workMachineHiden' => 0,
                    '$planTimeValue' => $planTimeValue,
                    '$planTimeHiden' => $planTimeHiden
                ];

            }

            $statusArray = [
                '1' => '待接单',
                '2' => '待分派',
                '3' => '生产中',
                '4' => '已完成',
                '101' => '待开工',
            ];
//            if($orderProcessInfo['status'] == 2 || $orderProcessInfo['status'] == 3){
            if (isset($orderProcessInfo['status']) && $orderProcessInfo['status'] && $orderProcessInfo['status'] != 1 && $orderProcessInfo['status'] != 101 && $orderProcessInfo['status'] != 2) {
                $statusValue = $statusArray[$orderProcessInfo['status']];
                $useColor = $blueColor;
                $androidBg = $androidBgBlue;
                $statusHiden = 0;
                $leftHiden = 0;
                $rightHiden = 0;
            } else {
                $statusValue = '';
                $useColor = $greColor;
                $androidBg = $androidBgGrey;
                $statusHiden = 1;
                $leftHiden = 0;
                $rightHiden = 0;
            }


            $list[] = [
                '$statusValue' => $statusValue,//'生产中'
                '$departmentValue' => $processTitle,//'彩印部门'
                '$leftHiden' => $leftHiden,
                '$rightHiden' => $rightHiden,
                '$statusHiden' => $statusHiden,
                '$departmentFontColor' => $useColor,
                '$statusViewBG' => $useColor,
                '$statusViewBorderColor' => $useColor,
                '$androidBg' => $androidBg
            ];
        }

        if ($orderInfo['status'] == 3) {//已经完成
            $statusValue = '已完成';
            $processTitle = '已完成';
            $useColor = $blueColor;
            $androidBg = $androidBgBlue;
            $statusHiden = 0;
            $leftHiden = 0;
            $rightHiden = 1;
        } else {
            $statusValue = '已完成';
            $processTitle = '已完成';
            $useColor = $greColor;
            $androidBg = $androidBgGrey;
            $statusHiden = 1;
            $leftHiden = 0;
            $rightHiden = 1;
        }
        $list[] = [
            '$statusValue' => $statusValue,//'生产中'
            '$departmentValue' => $processTitle,//'彩印部门'
            '$leftHiden' => $leftHiden,
            '$rightHiden' => $rightHiden,
            '$statusHiden' => $statusHiden,
            '$departmentFontColor' => $useColor,
            '$statusViewBG' => $useColor,
            '$statusViewBorderColor' => $useColor,
            '$androidBg' => $androidBg
        ];

        $tabviewSource = array_reverse($tabviewSource);
        //获取工序对应的详细信息
        //获取工序类型名称
        $orderTypeTitle = OrderType::getOneValueById($orderInfo['order_type'], 'title');

        $orderInfo['order_title'] = \App\Engine\Common::changeSnCode($orderInfo['order_title']);
        $returnApe = [
            'pageID' => 4,
            'data' => [
                '$productImage' => $exampleImg,
                '$productNameValue' => $orderTypeTitle,
                '$productOrderValue' => '生产单号:' . $orderInfo['order_title'],
                '$imageClickFunctionName' => 'imageClickAction' . $orderInfo['id'],
                '$lookOrderDetaileFunctionName' => 'lookOrderDetaile' . $orderInfo['id'],
                '$tabviewSource' => $tabviewSource,
                '$list' => $list
            ]
        ];
        return $returnApe;
    }

    //管理员工单详情-多工序列表展示
    public function getManagerOrderDetailList(Request $request)
    {
        //获取传入数据
        $input = $request->all();
        $input['order_id'] = isset($input['order_id']) ? $input['order_id'] : '';//工单-id

        //获取工单信息
        $orderInfo = Order::where('id', $input['order_id'])->first()->toArray();

        //工单基础信息字段，目前格式固定
        $orderBaseFieldList = $this->orderBaseFieldList();

        $listAll = [];
        $baseInfoList = [];
        //基本信息先固定

        foreach ($orderBaseFieldList as $key => $row) {
            $leftLabelValue = $row['title'];
            if ($row['field_type'] == 9) {//图片处理
                continue;//先不处理
            } elseif ($row['field_type'] == 5) {//填写+单位选择 处理
                $rightLabelValue = $orderInfo[$row['field_name']];
                $tmpArr = explode(',', $rightLabelValue);
                $rightLabelValue = '';
                foreach ($tmpArr as $tmpValue) {
                    $rightLabelValue .= $tmpValue;
                }
            } elseif ($row['field_type'] == 8) {//配送地址 处理
                continue;//另外处理
            } elseif ($row['field_type'] == 6) {//开关按钮
                $rightLabelValue = $orderInfo[$row['field_name']];
                $rightLabelValue = ($rightLabelValue == 1) ? '是' : '否';
            } else {
                $rightLabelValue = $orderInfo[$row['field_name']];
            }
            $baseInfoList[] = [
                '$leftLabelValue' => $leftLabelValue,
                '$rightLabelValue' => $rightLabelValue
            ];
        }
        //追加配送地址
        $orderDistributionRow = OrderDistribution::where(['order_id' => $input['order_id']])->first();
        if (!empty($orderDistributionRow)) {
            $baseInfoList[] = [
                '$leftLabelValue' => '收货人',
                '$rightLabelValue' => $orderDistributionRow['consignee']
            ];
            $baseInfoList[] = [
                '$leftLabelValue' => '收货人-手机号',
                '$rightLabelValue' => $orderDistributionRow['phone']
            ];
            $baseInfoList[] = [
                '$leftLabelValue' => '区县地址',
                '$rightLabelValue' => $orderDistributionRow['province_name'] . ' ' . $orderDistributionRow['city_name'] . ' ' . $orderDistributionRow['area_name']
            ];
            $baseInfoList[] = [
                '$leftLabelValue' => '收货人详细地址',
                '$rightLabelValue' => $orderDistributionRow['address']
            ];
        }

        $listAll[] = [
            '$titleLabelValue' => '基本信息',
            '$list' => $baseInfoList
        ];

        //动态获取工序数据
        //获取工单对应的所有工序
        $orderProcessList = OrderType::getAllOrderTypeProcess($orderInfo['order_type']);
        foreach ($orderProcessList as $processId) {
            //获取工序信息
            $orderProcessInfo = OrderProcess::where(['order_id' => $orderInfo['id'], 'process_type' => $processId])->first()->toArray();
            $processTitle = Process::getOneValueById($orderProcessInfo['process_type'], 'title');
            $preProcessEstimatedTime = $orderProcessInfo['start_time'] + $orderProcessInfo['estimated_time_hour'] * 3600 + $orderProcessInfo['estimated_time_minute'] * 60;

            $list = [];
            //通过字段类型不同处理
            //获取字段对应的类型1=>'文本',2=>'文本域',3=>'下拉框-跳界面',4=>'跳材料',5=>'有单位',6=>'开关',7=>'时间'
            $processFieldList = Process::getFieldListByProcessId($orderProcessInfo['process_type']);
            foreach ($processFieldList as $processFieldRow) {
                $tmpFiledType = $processFieldRow['field_type'];
                $showTitle = $orderProcessInfo[$processFieldRow['field_name']];//默认展示字段的内容

                if ($tmpFiledType == 4) {//材料选择暂时不显示在
                    continue;
                }

                $showTitle = OrderEngine::getOrderFiledValueTrue($orderProcessInfo[$processFieldRow['field_name']], $tmpFiledType);


                $list[] = [
                    '$leftLabelValue' => $processFieldRow['title'],
                    '$rightLabelValue' => $showTitle,
                ];
            }
            $listAll[] = [
                '$titleLabelValue' => $processTitle,
                '$list' => $list
            ];
        }

        $returnApe = [
            'pageID' => 1,
            'data' => [
                '$listAll' => $listAll
            ]
        ];
        return $returnApe;
    }


    //工单派发(下单人给工序管理员)
    public function orderConfirmAssignment()
    {
        $orderIds = request('order_ids');//工单id
        $orderIdArr = explode(",", $orderIds);
        $assignUser = \GuzzleHttp\json_decode(htmlspecialchars_decode(request('assign_user')), true);

        $userId = Func::getHeaderValueByName('userid');
        $userInfo = DepartmentUser::getCurrentInfo($userId)->toArray();

        //分配结果
        foreach ($orderIdArr as $orderId) {
            if (!trim($orderId)) {//过滤空格，不考虑orderId为0
                continue;
            }
            //获取工单详情
            $tmpOrderObj = Order::where(['id' => $orderId])->first();

            //只允许未派单的工单派发
            if ($tmpOrderObj->status != 4) {
                return [
                    'code' => 1,
                    'msg' => '工单已派发，请刷新页面'
                ];
            }

            $tmpOrderRow = $tmpOrderObj->toArray();


            $orderTitle = $tmpOrderRow['order_title'];
            $orderTypeId = $tmpOrderRow['order_type'];
            $companyId = $tmpOrderRow['company_id'];
            $foreignKey = intval($tmpOrderRow['customer_order_id']);

            //限制重复分派工单
            $isAllAssign = 1;//是否都已经派发
            $orderProcessList = OrderProcess::where(['order_id' => $orderId])->get()->toArray();
            foreach ($orderProcessList as $orderProcessRow) {
                if (!$orderProcessRow['uid']) {
                    $isAllAssign = 0;
                }
            }

            if ($isAllAssign) {
                return [
                    'code' => 1,
                    'msg' => '工单已派发，请刷新页面'
                ];
            }


            //下单人给管理员发消息
            $orderInfoProductNum = $tmpOrderRow['product_num'];
            $orderInfoProductNum = str_replace(',', '', $orderInfoProductNum);

            $orderInfoSpecification = $tmpOrderRow['finished_specification'];
            if ($orderInfoSpecification) {
                $orderInfoSpecification = str_replace(',', '×', $orderInfoSpecification);
                $orderInfoSpecification .= '厘米';
            }

            //片料规格chip_specification_length
            $orderChipSpecificationLength = $tmpOrderRow['chip_specification_length'];
//            $orderChipSpecificationLength = \App\Engine\OrderEngine::getOrderFiledValueTrue($tmpOrderRow['chip_specification_length'], 15);
            //格式调整
            //宽长
            $tmpValue = '';
            $tmpArr  = explode(',', $orderChipSpecificationLength);
            if (!empty($tmpArr) && (count($tmpArr) == 2)) {
                $tmpValue = sprintf("%s×%s厘米", $tmpArr[0], $tmpArr[1]);
            }
            $orderChipSpecificationLength = $tmpValue;


            ////追加功能，给没有设置分派角色的工序增加默认工序管理员（下单人）
            $result = OrderType::getAllStepsWithDistribution($tmpOrderRow['order_type']);
            //获取工序可分派给工序管理员的列表
            $result->transform(function ($item) {
//            $item->distributionUser = Privilege::getWithDepartmentUser( $item->distribution );
                $distributionUser = DepartmentUser::getWithPrivilege($item->distribution);
                $process_id = $item->process_id;
                $distributionUser->transform(function ($item) use ($process_id) {
                    $item->process_id = $process_id;
                    $item->ygtUser->avatar = $item->ygtUser->avatar ? Func::getImgUrlById($item->ygtUser->avatar) : asset('upload/appicon/logo.png');
                    return $item;
                });
                $item->distributionUser = $distributionUser->toArray();
                return $item;
            });

            $noAssignProcessIdList = [];//无需分派的工序id列表
            foreach ($result as $tmpValue) {
                if (empty($tmpValue['distributionUser'])) {
                    $noAssignProcessIdList[] = $tmpValue['process_id'];
                    //先分配工单给自己
                    $orderProcessCollectionList = OrderProcess::where(['order_id' => $orderId, 'process_type' => $tmpValue['process_id']])->get();
                    foreach ($orderProcessCollectionList as $orderProcessCollectionRow) {
                        $orderProcessCollectionRow->uid = $tmpOrderRow['uid'];
                        $orderProcessCollectionRow->save();
                    }
                }
            }

            //分配用户
            foreach ($assignUser as $assignUserRow) {
                $tmpProcessId = $assignUserRow['process_id'];
                $orderProcess = OrderProcess::firstOrNew(['order_id' => $orderId, 'process_type' => $tmpProcessId]);
                if ($orderProcess->count()) {
                    $uid = $assignUserRow['uid'];
                    $orderProcess->uid = $uid;
                    $orderProcess->save();
                }
            }

            //获取下单人信息
            $userRow = DepartmentUser::getCurrentInfo($tmpOrderRow['uid'])->toArray();

            //获取第一道步骤涉及的工序
            $processFirstList = OrderType::getFirstProcessBag($tmpOrderRow['order_type'])->toArray();
            //获取工单对应的工单工序列表
            $tmpOrderProcessList = OrderProcess::where(['order_id' => $orderId])->get();

            $needNextAssign = 0;//是否需要下一步分派（分派员工工单）
            foreach ($tmpOrderProcessList as $tmpOrderProcessRow) {
                //获取工序对应的权限用户
                $processId = $tmpOrderProcessRow['process_type'];

                ////调整为分派完订单同时发消息
//                if (in_array($tmpOrderProcessRow['process_type'], $processFirstList)) {//给第一道工艺的人发信息
                ////调整为下单人也需要分派指定员工（再下一步进行派发）--20180301 16:44
                if (in_array($tmpOrderProcessRow['process_type'], $noAssignProcessIdList)) {//未分派工序管理员，直接分派给员工
                    $needNextAssign = 1;

                    //自动派发给员工的订单不修改订单状态为已接单
                    //调整：无工序管理员订单，员工开工后再修改工序订单状态,订单状态修改为待开工
//                        //修改工序工单状态为2（已接单）
//                        $tmpOrderProcessRow->status = 101;
//                        $tmpOrderProcessRow->save();

                } else {//分派给工序管理员
                    //存入工单列表关联表
                    OrderEngine::importProcessManagerOrder($tmpOrderProcessRow->toArray());
                    $fieldName23 = $this->changeFieldName23($tmpOrderRow['field_name_23']);
                    $productName = \App\Engine\OrderEngine::getOrderFiledValueTrue($tmpOrderRow['product_name'], 20);
                    $messageContent = "单位名称：{$fieldName23}rnrn品名：{$productName}rnrn";
                    $messageContent .= "成品规格：{$orderInfoSpecification}rnrn";
                    $messageContent .= "片料规格：{$orderChipSpecificationLength}rnrn";
                    $messageContent .= "数量：{$orderInfoProductNum}rnrn";
                    $messageContent .= "交货日期：{$tmpOrderRow['finished_date']}rnrn";

                    //追加材料消息
                    $materialIdList = \App\Engine\OrderEngine::getProcessMaterialIdList($tmpOrderProcessRow['id']);
                    if (!empty($materialIdList)) {
                        $messageContent .= "工单需使用以下材料：rnrn";
                        //获取所有材料信息
                        foreach ($materialIdList as $tmpMaterialId) {
                            //获取材料信息
                            $tmpMaterialRow = \App\Engine\Product::getProductInfo($tmpMaterialId);
                            $tmpMaterialName = $tmpMaterialRow['product_name'];
                            $tmpMaterialNum = $tmpMaterialRow['number'];
                            $tmpMaterialUnit = $tmpMaterialRow['unit'];

                            $messageContent .= "{$tmpMaterialName} 【库存】{$tmpMaterialNum}（{$tmpMaterialUnit}）rnrn";
                        }
                    }

                    $data = [
                        'company_id' => $tmpOrderProcessRow['company_id'],
                        'privilege_id' => '',
                        'form_user_id' => $userId,
                        'to_user_id' => $tmpOrderProcessRow['uid'],
                        'foreign_key' => $foreignKey,
                        'type' => 2,
                        'type_id' => $tmpOrderProcessRow['id'],
                        'title' => $orderTitle,
                        'content' => $messageContent
                    ];
                    \App\Eloquent\Ygt\UserMessage::sendCustomerOrderMessage($data);
                }

                //给此步骤有查看权限的人发消息
                $processId = $tmpOrderProcessRow['process_type'];
                $orderTypeId = $tmpOrderRow['order_type'];
                $privilegeIds = PermissionEngine::getStepActionPrivilegeIdsByOrderTypeProcess($orderTypeId, $processId, 1);//1:查看;2:可写;3:分配;4:提交;5:转发;

                //存入工单列表关联表
                OrderEngine::importProcessSeeOrder($tmpOrderProcessRow->toArray(), $privilegeIds);

                //批量给所有角色发
                $fieldName23 = $this->changeFieldName23($tmpOrderRow['field_name_23']);
                $productName = \App\Engine\OrderEngine::getOrderFiledValueTrue($tmpOrderRow['product_name'], 20);

                $messageContent = "单位名称：{$fieldName23}rnrn品名：{$productName}rnrn";
                $messageContent .= "成品规格：{$orderInfoSpecification}rnrn数量：{$orderInfoProductNum}rnrn";
                $messageContent .= "交货日期：{$tmpOrderRow['finished_date']}";
                foreach ($privilegeIds as $val) {
                    $data = [
                        'company_id' => $tmpOrderProcessRow['company_id'], 'privilege_id' => $val,
                        'form_user_id' => $userId, 'to_user_id' => '',
                        'foreign_key' => $foreignKey,
                        'type' => 9, 'type_id' => $tmpOrderProcessRow['id'],
                        'title' => $orderTitle, 'content' => $messageContent
                    ];
                    UserMessage::sendCustomerOrderMessage($data);
                }

//                }
            }

            ////调整-如果还有员工需分派，主工单状态先不调整
            if (!$needNextAssign) {
                //修改工单状态
                $tmpOrderObj->status = 1;
                $tmpOrderObj->save();

                //修改订单状态
                $customerOrderId = $tmpOrderObj->customer_order_id;
                \App\Engine\OrderEngine::changeCustomerOrderStatus($customerOrderId, 3);//修改状态为待生产

                //修改工单列表关联表数据状态
                $type = 1;
                $relateId = $tmpOrderObj->id;
                $status = 1;
                OrderEngine::changeOrderListRelationStatus($type, $relateId, $status);
                OrderEngine::changeMainOrderTime($relateId, time());


                ////发送消息给采购
                //获取采购权限的角色
                $orderPreRow = $tmpOrderRow;

                //消息内容中用到的一些信息[减少sql查询],变量[拼音首字母]结合后面的文字注释,!!!!!!!!!!懒省事
                $msgDwmc        = \App\Engine\OrderEngine::getOrderFiledValueTrue($orderPreRow['field_name_23'], 19);//单位名称
                $msgGxmc        = \App\Engine\OrderType::getOneValueById($orderPreRow['order_type'], 'title');//工艺名称
                $msgPm          = \App\Engine\OrderEngine::getOrderFiledValueTrue($orderPreRow['product_name'], 20);//品名
                $msgPlgg        = \App\Engine\OrderEngine::getOrderFiledValueTrue($orderPreRow['chip_specification_length'], 15);//片料规格
                $msgSl          = \App\Engine\OrderEngine::getOrderFiledValueTrue($orderPreRow['product_num'], 5);//数量
                $msgJhrq        = $orderPreRow['finished_date'];//交货日期
                $msgCpzl        = isset($orderPreRow['finished_weight']) ? $orderPreRow['finished_weight'] : '';//成品重量,不确定字段!!!!!!!!!
                //$msgDwmc-单位名称-$msgGxmc-工艺名称-$msgPm-品名-$msgPlgg-片料规格-$msgSl-数量-$msgJhrq-交货日期
                //////////////////////////////////////////////

                //有材料的时候才发消息给采购和仓库
                //获取工单材料列表
                $tmpMaterialList = \App\Eloquent\Ygt\OrderMaterial::where(['order_id' => $orderId])->get();
                if(!empty($tmpMaterialList->toArray())){

                    //成品重量处理
                    $tmpArr = explode(',',$msgCpzl);
                    if(count($tmpArr) == 2){
                        if($tmpArr[0]){
                            $msgCpzl = $tmpArr[0].$tmpArr[1];
                        }else{
                            $msgCpzl = '';
                        }
                    }

                    //采购
                    //单位名称、工艺名称、品名、片料规格、数量、交货日期
                    //$msgDwmc-单位名称-$msgGxmc-工艺名称-$msgPm-品名-$msgPlgg-片料规格-$msgSl-数量-$msgJhrq-交货日期
                    $messageContent = "有新的工单";
                    $messageContent .= 'rnrn单位名称:' . $msgDwmc;//单位名称
                    $messageContent .= 'rnrn工艺名称:' . $msgGxmc;//工艺名称
                    $messageContent .= 'rnrn品名:' .$msgPm;//品名
                    $messageContent .= 'rnrn片料规格:' .$msgPlgg;//片料规格
                    $messageContent .= 'rnrn数量:' .$msgSl;//数量
                    $messageContent .= 'rnrn交货日期:' . $msgJhrq;//交货日期

                    $privilegeList = \App\Engine\OrderEngine::getPrivilegeByNode($companyId, 10);

                    foreach ($privilegeList as $privilegeId) {
                        $data = [
                            'company_id' => $companyId,
                            'privilege_id' => $privilegeId,
                            'form_user_id' => $userId,
                            'to_user_id' => '',
                            'foreign_key' => $foreignKey,
                            'type' => 23,//发送给采购员的消息
                            'type_id' => $orderId,
                            'title' => $orderPreRow['order_title'],
                            'content' => $messageContent,
                            'type_status' => 1,
                        ];
                        UserMessage::sendCustomerOrderMessage($data);
                    }

                    /** 添加材料到待采购列表中  zhuyujun 20181130 **/
                    $tmpObj = \App\Eloquent\Ygt\WaitPurchase::firstOrNew(['id'=>'']);
                    $tmpInsertRow = [
                        'order_id' => $orderId,
                        'type' => 1,
                        'status' => 1,
                        'uid' => $userId,
                        'company_id' => $companyId,
                    ];
                    $tmpObj->fill($tmpInsertRow);
                    $tmpObj->save();
                    $tmpWaitPurchaseId = $tmpObj->id;



                    foreach ($tmpMaterialList as $tmpMaterialRow){
                        $tmpObj = \App\Eloquent\Ygt\WaitPurchaseMaterial::firstOrNew(['id'=>'']);
                        $tmpInsertRow = [
                            'wait_purchase_id' => $tmpWaitPurchaseId,
                            'material_id' => $tmpMaterialRow['material_id'],
                        ];
                        $tmpObj->fill($tmpInsertRow);
                        $tmpObj->save();
                    }


                    //仓库
                    //单位名称、工艺名称、品名、片料规格、数量、交货日期
                    //$msgDwmc-单位名称-$msgGxmc-工艺名称-$msgPm-品名-$msgPlgg-片料规格-$msgSl-数量-$msgJhrq-交货日期
                    $messageContent = "有新的工单";
                    $messageContent .= 'rnrn单位名称:' . $msgDwmc;//单位名称
                    $messageContent .= 'rnrn工艺名称:' . $msgGxmc;//工艺名称
                    $messageContent .= 'rnrn品名:' . $msgPm;//品名
                    $messageContent .= 'rnrn片料规格:' . $msgPlgg;//片料规格
                    $messageContent .= 'rnrn数量:' . $msgSl;//数量
                    $messageContent .= 'rnrn交货日期:' . $msgJhrq;//交货日期

                    $privilegeList = \App\Engine\OrderEngine::getPrivilegeByNode($companyId, 7);
                    foreach ($privilegeList as $privilegeId) {
                        $data = [
                            'company_id' => $companyId,
                            'privilege_id' => $privilegeId,
                            'form_user_id' => $userId,
                            'to_user_id' => '',
                            'foreign_key' => $foreignKey,
                            'type' => 23,//发送给采购员的消息
                            'type_id' => $orderId,
                            'title' => $orderPreRow['order_title'],
                            'content' => $messageContent,
                            'type_status' => 1,
                        ];
                        UserMessage::sendCustomerOrderMessage($data);
                    }
                }



                //财务
                //客户名称、数量、交货日期、订单金额
                //$msgDwmc-单位名称-$msgGxmc-工艺名称-$msgPm-品名-$msgPlgg-片料规格-$msgSl-数量-$msgJhrq-交货日期
                $messageContent = "有新的工单";
                $messageContent .= 'rnrn客户名称:' . \App\Engine\OrderEngine::getOrderFiledValueTrue($orderPreRow['customer_name'], 18);//客户名称
                $messageContent .= 'rnrn数量:' . $msgSl;//数量
                $messageContent .= 'rnrn交货日期:' .$msgJhrq;//交货日期

                //获取订单金额
                $customerOrderPrices = '';
                $tmpObj = \App\Eloquent\Ygt\CustomerOrderPrice::where(['id' => $orderPreRow['customer_order_id']])->first();
                if ($tmpObj) {
                    $customerOrderPrices = $tmpObj->deal_price;
                }

                $messageContent .= 'rnrn订单金额:' . $customerOrderPrices;//订单金额

                $privilegeList = \App\Engine\OrderEngine::getPrivilegeByNode($companyId, 11);
                foreach ($privilegeList as $privilegeId) {
                    $data = [
                        'company_id' => $companyId,
                        'privilege_id' => $privilegeId,
                        'form_user_id' => $userId,
                        'to_user_id' => '',
                        'foreign_key' => $foreignKey,
                        'type' => 29,//发送给采购员的消息
                        'type_id' => $orderId,
                        'title' => $orderPreRow['order_title'],
                        'content' => $messageContent,
                        'type_status' => 1,
                    ];
                    UserMessage::sendCustomerOrderMessage($data);
                }
                //38=>'生产派单',//下单人生产派单时给发货员发消息---2018-8-28新增
                //下单派发工单后，发货员也需要像财务一样收到工单消息，消息详情内容：工艺名称、品名、成品规格、成品重量、下单数量、交货日期和收货信息
                //$msgDwmc-单位名称-$msgGxmc-工艺名称-$msgPm-品名-$msgPlgg-片料规格-$msgSl-数量-$msgJhrq-交货日期
                $orderAddress       = OrderDistribution::where(['order_id' => $orderPreRow['id']])->first();
                $msgOrderAddress    = '';
                if($orderAddress)
                {
                    $msgOrderAddress    = $orderAddress['province_name'].$orderAddress['city_name'].$orderAddress['area_name'].$orderAddress['address'];
                }
                $messageContent = "有新的工单";
                $messageContent .= 'rnrn工艺名称:' . $msgGxmc;
                $messageContent .= 'rnrn品名:' . $msgPm;
                $messageContent .= 'rnrn成品规格:' . $orderInfoSpecification;
                $messageContent .= 'rnrn成品重量:' . $msgCpzl;
                $messageContent .= 'rnrn下单数量:' . $msgSl;
                $messageContent .= 'rnrn交货日期:' . $msgJhrq;
                $messageContent .= 'rnrn收货信息:' .$msgOrderAddress;
                $msgArr             = [
                    'company_id' => $companyId,
                    'form_user_id' => $userId,
                    'to_user_id' => '',
                    'foreign_key' => $foreignKey,
                    'type' => 38,
                    'type_id' => $orderId,
                    'title' => $orderPreRow['order_title'],
                    'content' => $messageContent,
                    'type_status' => 1,
                ];
                $msgType            = 38;
                $this->sendMessageByType($msgArr,$msgType);
            }

        }

        //判断是否是订单转工单
        $isCustomerOrderToOrder = 0;//是否是订单转工单 1-是 0-不是
        if (isset($tmpOrderRow['customer_order_id']) && $tmpOrderRow['customer_order_id']) {
            $isCustomerOrderToOrder = 1;
        }

        return [
            'code' => 0,
            'msg' => '操作成功',
            'need_next_assign' => $needNextAssign, //是否需要下一步分派 0-不需要 1-需要
            'isCustomerOrderToOrder' => $isCustomerOrderToOrder,//是否是订单转工单 1-是 0-不是
        ];
    }


    //下单人给分派员工工单-基础页面
    public function manageOrderCourseAssignment()
    {
        $orderTypeId = request('order_type');

        $result = OrderType::getAllStepsWithDistribution($orderTypeId);

        $result = $result->filter(function ($item) {
            if ($item->distribution->toArray()) {
                return false;
            } else {
                return true;
            }
        });

        $result->transform(function ($item) {

            $tijiaoPrivilegeIds = PermissionEngine::getStepActionPrivilegeIds(4, $item->id);

            $distributionUser = DepartmentUser::getWithPrivilege($tijiaoPrivilegeIds);

            $process_id = $item->process_id;
            $distributionUser->transform(function ($item) use ($process_id) {
                $item->process_id = $process_id;
                $item->ygtUser->avatar = $item->ygtUser->avatar ? Func::getImgUrlById($item->ygtUser->avatar) : asset('upload/appicon/logo.png');
                return $item;
            });
            $item->user = $distributionUser->toArray();
            return $item;
        });

        return $result->values();

    }

    //下单人给分派员工工单-提交
    public function manageOrderCourseAssignmentSubmit()
    {

        $orderId = request('order_id');//工单id
        $assignUser = \GuzzleHttp\json_decode(htmlspecialchars_decode(request('assign_user')), true);

        $userId = Func::getHeaderValueByName('userid');
        $userInfo = DepartmentUser::getCurrentInfo($userId)->toArray();

        //分配结果
        //获取工单详情
        $orderRow = Order::where(['id' => $orderId])->first()->toArray();
        $orderTitle = $orderRow['order_title'];
        $orderTypeId = $orderRow['order_type'];
        $companyId = $orderRow['company_id'];
        $foreignKey = $orderRow['customer_order_id'];

        //只允许未派单的工单派发
        if ($orderRow['status'] != 4) {
            return [
                'code' => 1,
                'msg' => '工单已派发，请刷新页面'
            ];
        }

        //分配员工
        foreach ($assignUser as $assignUserRow) {
            $processId = $assignUserRow['process_id'];
            $orderProcessRow = OrderProcess::where(['order_id' => $orderId, 'process_type' => $processId])->first()->toArray();
            $orderProcessId = $orderProcessRow['id'];

            $processId = $orderProcessRow['process_type'];//工序id

            //只有工序工单状态为1或2时才允许派发工单
            if ($orderProcessRow['status'] != 2 && $orderProcessRow['status'] != 1) {
                return [
                    'code' => 1,
                    'message' => '工单已派发，请刷新工单列表'
                ];
            }

            //获取用户id
            $uidList = explode(',', $assignUserRow['uid']);
            foreach ($uidList as $uid) {
                if (!$uid) {//空值过滤
                    continue;
                }

                $insertRow = [
                    'uid' => $uid,
                    'total_number' => 0,
                    'order_process_id' => $orderProcessId,
                    'assign_id' => $userId,//派发人id
//                    'status' => 2,//状态 1-待接单 调整为先领取材料 2-待领取材料
                    'status' => 1,//状态 1-待接单 调整为先领取材料 2-待领取材料 || 跳过领材阶段 20180707 zhuyujun
                    'company_id' => $orderProcessRow['company_id'],//状态 1-待接单
                ];

                $orderProcessCourse = OrderProcessCourse::firstOrNew(['order_process_id' => $orderProcessId, 'uid' => $uid]);
                $orderProcessCourse->fill($insertRow);
                $orderProcessCourse->save();
                $orderPorcessCourseId = $orderProcessCourse->id;

                //管理员给员工发消息
                $assignUserRow = DepartmentUser::getCurrentInfo($userId)->toArray();
                $orderInfoProductNum = $orderRow['product_num'];
                $orderInfoProductNum = str_replace(',', '', $orderInfoProductNum);
                $orderInfoSpecification = $orderRow['finished_specification'];
                if ($orderInfoSpecification) {
                    $orderInfoSpecification = str_replace(',', '×', $orderInfoSpecification);
                    $orderInfoSpecification .= '厘米';
                }
                $fieldName23 = $this->changeFieldName23($orderRow['field_name_23']);
                $productName = \App\Engine\OrderEngine::getOrderFiledValueTrue($orderRow['product_name'], 20);
                $messageContent = "单位名称：{$fieldName23}rnrn品名：{$productName}rnrn";
                $messageContent .= "工单号：{$orderTitle}rnrn";
                $messageContent .= "成品规格：{$orderInfoSpecification}rnrn数量：{$orderInfoProductNum}rnrn";
                $messageContent .= "交货日期： {$orderRow['finished_date']}rnrn";

                //追加材料消息
                $materialIdList = \App\Engine\OrderEngine::getProcessMaterialIdList($orderProcessRow['id']);
                if (!empty($materialIdList)) {
                    $messageContent .= "工序用料：rnrn";
                    //获取所有材料信息
                    foreach ($materialIdList as $tmpMaterialId) {
                        //获取材料信息
                        //兼容集合材料
                        if(strstr($tmpMaterialId,'A')){
                            $tmpAssemblageMaterialId = str_replace('A','',$tmpMaterialId);
                            $tmpMaterialRow = \App\Eloquent\Ygt\AssemblageMaterial::withTrashed()->where(['id'=>$tmpAssemblageMaterialId])->first();
                            $tmpMaterialName = $tmpMaterialRow['product_name'];
                            $tmpMaterialNum = $tmpMaterialRow['number'];
                            $tmpMaterialUnit = $tmpMaterialRow['unit'];
                        }else{
                            $tmpMaterialRow = \App\Engine\Product::getProductInfo($tmpMaterialId);
                            $tmpMaterialName = $tmpMaterialRow['product_name'];
                            $tmpMaterialNum = $tmpMaterialRow['number'];
                            $tmpMaterialUnit = $tmpMaterialRow['unit'];
                        }

                        $messageContent .= "{$tmpMaterialName} 【库存】{$tmpMaterialNum}（{$tmpMaterialUnit}）rnrn";
                    }
                }else{
                    $messageContent .= "工序用料：无";
                }


                $processName = Process::getOneValueById($processId,'title');

                $data = [
                    'company_id' => $orderProcessRow['company_id'],
                    'privilege_id' => '',
                    'form_user_id' => $userId,
                    'to_user_id' => $uid,
                    'foreign_key' => $foreignKey,
                    'type' => 1,
                    'type_id' => $orderPorcessCourseId,
                    'title' => $orderTitle,
                    'content' => $messageContent,
                    'type_status' => 1,//状态 1-待接单 调整为先领取材料 2-待领取材料 || 跳过领材阶段 20180707 zhuyujun
//                    'theme'=>$processName.'工单'
                    'theme'=>'工单生产'
                ];
                $result = UserMessage::sendCustomerOrderMessage($data);

                //存入工单列表关联表
                OrderEngine::importProcessCourseOrder($orderProcessCourse->toArray());
            }

            //修改工单状态
            $orderProcess = OrderProcess::where(['id' => $orderProcessId])->first();
//        $orderProcess->status = 3;
            $orderProcess->status = 101;//增加新状态待开工
            $orderProcess->save();

            //修改工单列表关联表数据状态
            $type = 2;
            $relateId = $orderProcess->id;
//        $status = 3;
            $status = 101;//增加新状态待开工
            OrderEngine::changeOrderListRelationStatus($type, $relateId, $status);

            //如果下单人直接派发员工--修改主工单状态
            if ($orderRow['uid'] == $orderProcess['uid']) {
                //修改工单状态
                $orderObj = Order::where(['id' => $orderId])->first();
                if (!empty($orderObj->toArray())) {
                    $orderObj->status = 1;
                    $orderObj->save();

                    //修改订单状态
                    $customerOrderId = $orderObj->customer_order_id;
                    \App\Engine\OrderEngine::changeCustomerOrderStatus($customerOrderId, 3);//修改状态为待生产

                    //修改工单列表关联表数据状态
                    $type = 1;
                    $relateId = $orderObj->id;
                    $status = 1;
                    OrderEngine::changeOrderListRelationStatus($type, $relateId, $status);
                } else {
                    return [
                        'code' => 1,
                        'message' => '参数错误'
                    ];
                }
            }

            //更新工序管理员消息状态为3已分配待开工
            $typeUserId = $orderProcess->uid;
            $typeId = $orderProcess->id;
            UserMessage::updateTypeStatusByTypeId(2, $typeId, $typeUserId, 3);
        }


        //修改工单状态
        $tmpOrderObj = Order::where(['id' => $orderId])->first();
        $tmpOrderObj->status = 1;
        $tmpOrderObj->save();

        //修改工单列表关联表数据状态
        $type = 1;
        $relateId = $tmpOrderObj->id;
        $status = 1;
        OrderEngine::changeOrderListRelationStatus($type, $relateId, $status);
        OrderEngine::changeMainOrderTime($relateId, time());;
        //判断是否是订单转工单
        $isCustomerOrderToOrder = 0;//是否是订单转工单 1-是 0-不是
        if (isset($orderRow['customer_order_id']) && $orderRow['customer_order_id']) {
            $isCustomerOrderToOrder = 1;
        }


        ////发送消息给采购
        $orderPreRow = $orderRow;

        //消息内容中用到的一些信息[减少sql查询],变量[拼音首字母]结合后面的文字注释,!!!!!!!!!!懒省事
        $msgDwmc        = \App\Engine\OrderEngine::getOrderFiledValueTrue($orderPreRow['field_name_23'], 19);//单位名称
        $msgGxmc        = \App\Engine\OrderType::getOneValueById($orderPreRow['order_type'], 'title');//工艺名称
        $msgPm          = \App\Engine\OrderEngine::getOrderFiledValueTrue($orderPreRow['product_name'], 20);//品名
        $msgPlgg        = \App\Engine\OrderEngine::getOrderFiledValueTrue($orderPreRow['chip_specification_length'], 15);//片料规格
        $msgSl          = \App\Engine\OrderEngine::getOrderFiledValueTrue($orderPreRow['product_num'], 5);//数量
        $msgJhrq        = $orderPreRow['finished_date'];//交货日期
        $msgCpzl        = isset($orderPreRow['finished_weight']) ? $orderPreRow['finished_weight'] : '';//成品重量,不确定字段!!!!!!!!!
        $msgMaterial    = '';

        //有材料的时候才发消息给采购和仓库
        //获取工单材料列表
        $tmpMaterialList = \App\Eloquent\Ygt\OrderMaterial::where(['order_id' => $orderId])->get();
        if(!empty($tmpMaterialList->toArray())){

            //获取采购权限的角色
            //////////////////////////////////////////////

            //获取材料信息
            foreach($tmpMaterialList as $tmpMaterial){
                //获取材料信息
                $tmpMaterialRow = \App\Engine\Product::getProductInfo($tmpMaterial['material_id']);
                $msgMaterial.=$tmpMaterialRow['product_name'].' ';
            }


            //成品重量处理
            $tmpArr = explode(',',$msgCpzl);
            if(count($tmpArr) == 2){
                if($tmpArr[0]){
                    $msgCpzl = $tmpArr[0].$tmpArr[1];
                }else{
                    $msgCpzl = '';
                }
            }

            //$msgDwmc-单位名称-$msgGxmc-工艺名称-$msgPm-品名-$msgPlgg-片料规格-$msgSl-数量-$msgJhrq-交货日期
            //////////////////////////////////////////////
            //采购
            //单位名称、工艺名称、品名、片料规格、数量、交货日期
            //$msgDwmc-单位名称-$msgGxmc-工艺名称-$msgPm-品名-$msgPlgg-片料规格-$msgSl-数量-$msgJhrq-交货日期
            $messageContent = "有新的工单";
            $messageContent .= 'rnrn单位名称:' . $msgDwmc;//单位名称
            //$messageContent .= 'rnrn工艺名称:' . $msgGxmc;//工艺名称
            $messageContent .= 'rnrn品名:' . $msgPm;//品名
            //$messageContent .= 'rnrn片料规格:' . $msgPlgg;//片料规格
            $messageContent .= 'rnrn工单号:'.$orderTitle;
            $messageContent .= 'rnrn数量:' . $msgSl;//数量
            $messageContent .= 'rnrn交货日期:' . $msgJhrq;//交货日期
            $messageContent .= 'rnrn材料列表:'.$msgMaterial;

            $privilegeList = \App\Engine\OrderEngine::getPrivilegeByNode($companyId, 10);
            foreach ($privilegeList as $privilegeId) {
                $data = [
                    'company_id' => $companyId,
                    'privilege_id' => $privilegeId,
                    'form_user_id' => $userId,
                    'to_user_id' => '',
                    'foreign_key' => $foreignKey,
                    'type' => 23,//发送给采购员的消息
                    'type_id' => $orderId,
                    'title' => $orderPreRow['order_title'],
                    'content' => $messageContent,
                    'type_status' => 1,
                    'theme'=>'工单所需用料'
                ];
                UserMessage::sendCustomerOrderMessage($data);
            }


            //仓库
            //单位名称、工艺名称、品名、片料规格、数量、交货日期
            //$msgDwmc-单位名称-$msgGxmc-工艺名称-$msgPm-品名-$msgPlgg-片料规格-$msgSl-数量-$msgJhrq-交货日期
            $messageContent = "有新的工单";
            $messageContent .= 'rnrn单位名称:' . $msgDwmc;//单位名称
            //$messageContent .= 'rnrn工艺名称:' . $msgGxmc;//工艺名称
            $messageContent .= 'rnrn品名:' . $msgPm;//品名
            //$messageContent .= 'rnrn片料规格:' . $msgPlgg;//片料规格
            $messageContent .= 'rnrn工单号:'.$orderTitle;
            $messageContent .= 'rnrn数量:' . $msgSl;//数量
            $messageContent .= 'rnrn交货日期:' . $msgJhrq;//交货日期
            $messageContent .= 'rnrn材料列表:'.$msgMaterial;

            $privilegeList = \App\Engine\OrderEngine::getPrivilegeByNode($companyId, 7);
            foreach ($privilegeList as $privilegeId) {
                $data = [
                    'company_id' => $companyId,
                    'privilege_id' => $privilegeId,
                    'form_user_id' => $userId,
                    'to_user_id' => '',
                    'foreign_key' => $foreignKey,
                    'type' => 23,//发送给采购员的消息
                    'type_id' => $orderId,
                    'title' => $orderPreRow['order_title'],
                    'content' => $messageContent,
                    'type_status' => 1,
                    'theme'=>'工单所需用料'
                ];
                UserMessage::sendCustomerOrderMessage($data);
            }


            /** 添加材料到待采购列表中  zhuyujun 20181130 **/
            $tmpObj = \App\Eloquent\Ygt\WaitPurchase::firstOrNew(['id'=>'']);
            $tmpInsertRow = [
                'order_id' => $orderId,
                'type' => 1,
                'status' => 1,
                'uid' => $userId,
                'company_id' => $companyId,
            ];
            $tmpObj->fill($tmpInsertRow);
            $tmpObj->save();
            $tmpWaitPurchaseId = $tmpObj->id;


            foreach ($tmpMaterialList as $tmpMaterialRow){
                $tmpObj = \App\Eloquent\Ygt\WaitPurchaseMaterial::firstOrNew(['id'=>'']);
                $tmpInsertRow = [
                    'wait_purchase_id' => $tmpWaitPurchaseId,
                    'material_id' => $tmpMaterialRow['material_id'],
                ];
                $tmpObj->fill($tmpInsertRow);
                $tmpObj->save();
            }

        }


        //财务
        //客户名称、数量、交货日期、订单金额
        //$msgDwmc-单位名称-$msgGxmc-工艺名称-$msgPm-品名-$msgPlgg-片料规格-$msgSl-数量-$msgJhrq-交货日期
        $messageContent = "有新的工单";
        $messageContent .= 'rnrn客户名称:' . \App\Engine\OrderEngine::getOrderFiledValueTrue($orderPreRow['customer_name'], 18);//客户名称
        $messageContent .= 'rnrn单位名称:' . $msgDwmc;//单位名称
        $messageContent .= 'rnrn品名:' . $msgPm;//品名
        $messageContent .= 'rnrn工单号:'.$orderTitle;
        $messageContent .= 'rnrn数量:' . $msgSl;//数量
        $messageContent .= 'rnrn交货日期:' . $msgJhrq;//交货日期

        //获取订单金额
        $customerOrderPrices = '';
        $tmpObj = \App\Eloquent\Ygt\CustomerOrderPrice::where(['id' => $orderPreRow['customer_order_id']])->first();
        if ($tmpObj) {
            $customerOrderPrices = $tmpObj->deal_price;
        }

        if($msgSl > 0){
            $messageContent .= 'rnrn单价:' . sprintf('%2.f',$customerOrderPrices/$msgSl);//数量
        }else{
            $messageContent .= 'rnrn单价:' . sprintf('%2.f',0);//数量
        }

        $messageContent .= 'rnrn订单金额:' . $customerOrderPrices;//订单金额

        $privilegeList = \App\Engine\OrderEngine::getPrivilegeByNode($companyId, 11);
        foreach ($privilegeList as $privilegeId) {
            $data = [
                'company_id' => $companyId,
                'privilege_id' => $privilegeId,
                'form_user_id' => $userId,
                'to_user_id' => '',
                'foreign_key' => $foreignKey,
                'type' => 29,//下单人生产派单时给财务发消息
                'type_id' => $orderId,
                'title' => $orderPreRow['order_title'],
                'content' => $messageContent,
                'type_status' => 1,
                'theme'=>'工单开票需求预备'
            ];
            UserMessage::sendCustomerOrderMessage($data);
        }
        //38=>'生产派单',//下单人生产派单时给发货员发消息---2018-8-28新增
        //下单派发工单后，发货员也需要像财务一样收到工单消息，消息详情内容：工艺名称、品名、成品规格、成品重量、下单数量、交货日期和收货信息
        //$msgDwmc-单位名称-$msgGxmc-工艺名称-$msgPm-品名-$msgPlgg-片料规格-$msgSl-数量-$msgJhrq-交货日期
        $addressWhere = ['id' => $orderPreRow['field_name_22']];
        $orderAddress       = \App\Eloquent\Ygt\BuyersAddress::withTrashed()->where($addressWhere)->first();
        $msgOrderAddress    = '';
        if($orderAddress)
        {
            $msgOrderAddress    = $orderAddress['province_name'].$orderAddress['city_name'].$orderAddress['area_name'].$orderAddress['address'];
        }
        $messageContent = "有新的工单";
        $messageContent .= 'rnrn工艺名称:' . $msgGxmc;
        $messageContent .= 'rnrn品名:' . $msgPm;
        $messageContent .= 'rnrn成品规格:' . $orderInfoSpecification;
        $messageContent .= 'rnrn成品重量:' . $msgCpzl;
        $messageContent .= 'rnrn下单数量:' . $msgSl;
        $messageContent .= 'rnrn交货日期:' . $msgJhrq;
        $messageContent .= 'rnrn收货信息:' .$msgOrderAddress;
        $msgArr             = [
            'company_id' => $companyId,
            'form_user_id' => $userId,
            'to_user_id' => '',
            'foreign_key' => $foreignKey,
            'type' => 38,
            'type_id' => $orderId,
            'title' => $orderPreRow['order_title'],
            'content' => $messageContent,
            'type_status' => 1,
            'theme'=>'工单发货需求预备'
        ];
        $msgType            = 38;
        $this->sendMessageByType($msgArr,$msgType);

        return [
            'code' => 0,
            'message' => '分派成功',
            'isCustomerOrderToOrder' => $isCustomerOrderToOrder,//是否是订单转工单 1-是 0-不是
        ];

    }

    //工单删除
    public function orderDelete()
    {
        $orderIds = request('order_ids');//工单id
        $orderIdArr = explode(",", $orderIds);
        foreach ($orderIdArr as $orderId) {
            if (!trim($orderId)) {//过滤空格，不考虑orderId为0
                continue;
            }

            //删除工单列表表的数据
            OrderListRelation::where(['type' => 1, 'relate_id' => $orderId])->delete();
            $orderProcessIds = OrderProcess::where(['order_id' => $orderId])->get()->pluck('id');
            OrderListRelation::whereIn('type', [2, 3])->whereIn('relate_id', $orderProcessIds)->delete();
            //删除和该订单有关的所有消息
            $whereMessage = ['foreign_type' => 1, 'foreign_key' => $orderId];
            UserMessage::where($whereMessage)->delete();


            //删除主工单信息
            Order::where(['id' => $orderId])->delete();
            //删除工单派送信息
            OrderDistribution::where(['order_id' => $orderId])->delete();
            //删除工单工序信息
            OrderProcess::where(['order_id' => $orderId])->delete();

            //删除工单和版关联关系
            OrderPlate::where(['order_id' => $orderId])->delete();


        }

        return [
            'code' => 0,
            'msg' => '操作成功'
        ];
    }

    //工单再来一单
    public function copyOrder()
    {
        $oldOrderId = request('order_id');//旧工单id

        if (!$oldOrderId) {
            return [
                'code' => 1,
                'message' => '参数错误'
            ];
        }

        $curOrderRow = Order::where(['id' => $oldOrderId])->first()->toArray();

        //创建预生成工单&返回预生成工单id
        $orderPreRow = OrderPre::firstOrNew(['id' => '']);

        //生成工单号
        $orderTitle = 'D' . time() . rand(0, 9) . rand(0, 9) . rand(0, 9) . rand(0, 9) . rand(0, 9) . rand(0, 9);

        //用户id&企业id
        //$userId = request()->header('userid', 0);
        $userId = Func::getHeaderValueByName('userid');
        $userInfo = DepartmentUser::getCurrentInfo($userId)->toArray();
        $companyId = isset($userInfo['company_id']) ? $userInfo['company_id'] : '';

        $insertRow = [
            'order_type' => $curOrderRow['order_type'],
            'order_title' => $orderTitle,
            'uid' => $userId,
            'company_id' => $companyId,
        ];

        $orderPreRow->fill($insertRow);
        $orderPreRow->save();
        $orderPreId = $orderPreRow->id;

        //复制对应的工单派送地址
        $curOrderDistributionCollection = OrderDistribution::where(['order_id' => $curOrderRow['id']])->get();
        if ($curOrderDistributionCollection->count()) {//存在派送信息
            $curOrderDistributionCollectionRow = $curOrderDistributionCollection->first()->toArray();
            $curOrderDistributionCollectionRow['order_id'] = $orderPreId;
            $orderDistributionPreRow = OrderDistributionPre::firstOrNew(['id' => '']);
            $orderDistributionPreRow->fill($curOrderDistributionCollectionRow);
            $orderDistributionPreRow->save();
            $orderDistributionPreId = $orderDistributionPreRow->id;
        }

        return ['order_id' => $orderPreId];

    }

    //分派员工列表
    public function orderCourseAssignment()
    {
        //获取基本参数
        $orderPorcessId = request('order_process_id');//工单工序id
        $orderProcessRow = OrderProcess::where(['id' => $orderPorcessId])->first()->toArray();


        $orderId = $orderProcessRow['order_id'];//工单id
        $processId = $orderProcessRow['process_type'];//工序id

        //获取工单信息
        $orderRow = Order::where(['id' => $orderId])->first()->toArray();
        $orderType = $orderRow['order_type'];//工单类型

        //获取对应分配员工列表
        $privilegeId = PermissionEngine::getStepSubmitActionPrivilegeIds($orderType, $processId)->toArray();//角色id
        $userList = DepartmentUser::getListByPrivilegeId($privilegeId)->toArray();//被分配的员工列表


        $orderProcessNeedNum = \App\Engine\OrderEngine::getOrderPorcessNeedNum($orderProcessRow['process_type'],$orderRow);
        return [
            'completed_number' => $orderProcessNeedNum,//需完成数量（分派数量）
            'userList' => $userList,
        ];
    }

    //分派员工-数据提交（工序管理员分派给员工）
    public function orderCourseAssignmentSubmit()
    {
        //获取基本参数
        $orderProcessId = request('order_process_id');//工单id
        $assignUserList = \GuzzleHttp\json_decode(htmlspecialchars_decode(request('assign_user_list')), true);


        ////获取选中的员工&分派的数量
        //获取工单工序材料列表
        $orderProcessRow = OrderProcess::where(['id' => $orderProcessId])->first()->toArray();
        //用户id
        $userId = $orderProcessRow['uid'];

        $orderId = $orderProcessRow['order_id'];//工单id
        $processId = $orderProcessRow['process_type'];//工序id


        //是否为重新分派
        $isReset = request('is_reset');//是否为重新分派 1-是 0-不是
        $oldOrderProcessCourseId = $newOrderProcessCourseId = '';//用于重新分派工单后，领取材料不变

        if ($isReset) {//如果是重新分派，清除原来的员工工单消息
            if ($orderProcessRow['status'] == 3 || $orderProcessRow['status'] == 4) {//如果工序工单已经开工，限制重新分派
                return [
                    'code' => 2,
                    'message' => '员工已开工，限制重新分派给员工'
                ];
            } else {//清除原来的员工工单
                $where = [
                    'order_process_id' => $orderProcessId
                ];
                $orderProcessCourseObjList = OrderProcessCourse::where($where)->get();
                foreach ($orderProcessCourseObjList as $orderProcessCourseObj) {
                    if(!$oldOrderProcessCourseId){
                        $oldOrderProcessCourseId = $orderProcessCourseObj['id'];
                    }

                    //清理工单列表表的数据
                    $where = [
                        'type' => 4,
                        'relate_id' => $orderProcessCourseObj->id
                    ];
                    $orderListRelationObjList = OrderListRelation::where($where)->get();
                    foreach ($orderListRelationObjList as $orderListRelationObj) {
                        $orderListRelationObj->delete();
                    }

                    //清理消息
                    $courseUserId = $orderProcessCourseObj->uid;
                    $type = 1;
                    $typeId = $orderProcessCourseObj->id;
                    $result = UserMessage::deleteOneByTypeId($courseUserId, $type, $typeId);

                    $orderProcessCourseObj->delete();
                }
            }
        } else {//如果不是重新派发，限制重复派发（多次点击或者网络原因）
            if ($orderProcessRow['status'] != 2 && $orderProcessRow['status'] != 1) {
                return [
                    'code' => 1,
                    'message' => '工单已派发，请刷新页面'
                ];
            }
        }

        //只有工序工单状态为2时才允许派发工单
        if ($orderProcessRow['status'] != 2 && $orderProcessRow['status'] != 1 && $orderProcessRow['status'] != 101) {
            return [
                'code' => 1,
                'message' => '工单已派发，请刷新工单列表'
            ];
        }

        //工单信息
        $orderRow = Order::where(['id' => $orderId])->first()->toArray();
        $orderTitle = $orderRow['order_title'];
        $foreignKey = intval($orderRow['customer_order_id']);

        //插入数据
        foreach ($assignUserList as $userRow) {
            $insertRow = [
                'uid' => $userRow['uid'],
                'total_number' => $userRow['total_number'],
                'order_process_id' => $orderProcessId,
                'assign_id' => $userId,//派发人id
//                'status' => 2,//状态 1-待接单 调整为先领取材料 2-待领取材料
                'status' => 1,//状态 1-待接单 调整为先领取材料 2-待领取材料 || 跳过领材阶段 20180707 zhuyujun
                'company_id' => $orderRow['company_id'],//状态 1-待接单
            ];

            $orderProcessCourse = OrderProcessCourse::firstOrNew(['order_process_id' => $orderProcessId, 'uid' => $userRow['uid']]);
            $orderProcessCourse->fill($insertRow);
            $orderProcessCourse->save();
            $orderPorcessCourseId = $orderProcessCourse->id;

            if(!$newOrderProcessCourseId){
                $newOrderProcessCourseId = $orderPorcessCourseId;

                //修改材料关联关系
               $orderMaterialCourseObjList = \App\Eloquent\Ygt\OrderMaterialCourse::where(['order_process_course_id'=>$oldOrderProcessCourseId])->get();
               foreach ($orderMaterialCourseObjList as $orderMaterialCourseObj){
                   $orderMaterialCourseObj->order_process_course_id = $newOrderProcessCourseId;
                   $orderMaterialCourseObj->save();
               }
               
               //修改码的绑定关系
                $orderMaterialQrLogObjList = \App\Eloquent\Ygt\OrderMaterialQrLog::where(['order_process_course_id'=>$oldOrderProcessCourseId])->get();
                foreach ($orderMaterialQrLogObjList as $orderMaterialQrLogObj){
                    $orderMaterialQrLogObj->order_process_course_id = $newOrderProcessCourseId;
                    $orderMaterialQrLogObj->save();
                }
                
                //修改分次领取记录的关系
                $orderMaterialReceiveGradationObjList = \App\Eloquent\Ygt\OrderMaterialReceiveGradation::where(['order_process_course_id'=>$oldOrderProcessCourseId])->get();
                foreach ($orderMaterialReceiveGradationObjList as $orderMaterialReceiveGradationObj){
                    $orderMaterialReceiveGradationObj->order_process_course_id = $newOrderProcessCourseId;
                    $orderMaterialReceiveGradationObj->save();
                }

            }

            ////材料添加到员工材料表
//            $orderMaterialList = OrderMaterial::where(['order_id' => $orderId, 'process_type' => $processId])->get()->toArray();
//            foreach ($orderMaterialList as $orderMaterialRow) {
//                $orderMaterialCourse = OrderMaterialCourse::firstOrNew(['id' => '']);
//                unset($orderMaterialRow['order_id']);
//                unset($orderMaterialRow['uid']);
//                $orderMaterialRow['order_process_course_id'] = $orderPorcessCourseId;
//
//                $orderMaterialCourse->fill($orderMaterialRow);
//                $orderMaterialCourse->save();
//            }


            //管理员给员工发消息
            $assignUserRow = DepartmentUser::getCurrentInfo($userId)->toArray();
            $orderInfoProductNum = $orderRow['product_num'];
            $orderInfoProductNum = str_replace(',', '', $orderInfoProductNum);
            $orderInfoSpecification = $orderRow['finished_specification'];
            if ($orderInfoSpecification) {
                $orderInfoSpecification = str_replace(',', '×', $orderInfoSpecification);
                $orderInfoSpecification .= '厘米';
            }
            $fieldName23 = $this->changeFieldName23($orderRow['field_name_23']);
            $productName = \App\Engine\OrderEngine::getOrderFiledValueTrue($orderRow['product_name'], 20);

            //片料规格
            $tmpChipSpecificationLength = \App\Engine\OrderEngine::getOrderFiledValueTrue($orderRow['chip_specification_length'], 15);

//            $messageContent = "单位名称：{$fieldName23}rnrn品名：{$productName}rnrn";
//            $messageContent .= "成品规格：{$orderInfoSpecification}rnrn数量：{$orderInfoProductNum}rnrn";
//            $messageContent .= "交货日期： {$orderRow['finished_date']}";

            //工单号、单位名称、品名、片料规格、数量、交货日期、彩印用料
            $tmpOrderTitle = \App\Engine\Common::changeSnCode($orderRow['order_title']);
            $messageContent = "工单号:{$tmpOrderTitle}rnrn";
            $messageContent .= "单位名称:{$fieldName23}rnrn";
            $messageContent .= "品名:{$productName}rnrn";
            $messageContent .= "片料规格:{$tmpChipSpecificationLength}rnrn";
            $messageContent .= "数量:{$orderInfoProductNum}rnrn";
            $messageContent .= "交货日期:{$orderRow['finished_date']}rnrn";


            //追加材料消息
            $materialIdList = \App\Engine\OrderEngine::getProcessMaterialIdList($orderProcessRow['id']);
            if (!empty($materialIdList)) {
                $messageContent .= "工序用料：rnrn";
                //获取所有材料信息
                foreach ($materialIdList as $tmpMaterialId) {
                    //获取材料信息
                    //兼容集合材料
                    if(strstr($tmpMaterialId,'A')){
                        $tmpAssemblageMaterialId = str_replace('A','',$tmpMaterialId);
                        $tmpMaterialRow = \App\Eloquent\Ygt\AssemblageMaterial::withTrashed()->where(['id'=>$tmpAssemblageMaterialId])->first();
                        $tmpMaterialName = $tmpMaterialRow['product_name'];
                        $tmpMaterialNum = $tmpMaterialRow['number'];
                        $tmpMaterialUnit = $tmpMaterialRow['unit'];
                    }else{
                        $tmpMaterialRow = \App\Engine\Product::getProductInfo($tmpMaterialId);
                        $tmpMaterialName = $tmpMaterialRow['product_name'];
                        $tmpMaterialNum = $tmpMaterialRow['number'];
                        $tmpMaterialUnit = $tmpMaterialRow['unit'];
                    }


                    $messageContent .= "{$tmpMaterialName} 【库存】{$tmpMaterialNum}（{$tmpMaterialUnit}）rnrn";
                }
            }else{
                $messageContent .= "工序用料：无";
            }
            $data = [
                'company_id' => $orderProcessRow['company_id'],
                'privilege_id' => '',
                'form_user_id' => $userId,
                'to_user_id' => $userRow['uid'],
                'foreign_key' => $foreignKey,
                'type' => 1,
                'type_id' => $orderPorcessCourseId,
                'title' => $orderTitle,
                'content' => $messageContent,
                'type_status' => 1,//状态 1-待接单 调整为先领取材料 2-待领取材料 || 跳过领材阶段 20180707 zhuyujun
                'theme' => '工单生产',
            ];
            UserMessage::sendCustomerOrderMessage($data);

            //存入工单列表关联表
            OrderEngine::importProcessCourseOrder($orderProcessCourse->toArray());
        }

        //修改工单状态
        $orderProcess = OrderProcess::where(['id' => $orderProcessId])->first();
//        $orderProcess->status = 3;
        $orderProcess->status = 101;//增加新状态待开工
        $orderProcess->save();

        //修改工单列表关联表数据状态
        $type = 2;
        $relateId = $orderProcess->id;
//        $status = 3;
        $status = 101;//增加新状态待开工
        OrderEngine::changeOrderListRelationStatus($type, $relateId, $status);

        //如果下单人直接派发员工--修改主工单状态
        if ($orderRow['uid'] == $orderProcess['uid']) {
            //修改工单状态
            $orderObj = Order::where(['id' => $orderId])->first();
            if (!empty($orderObj->toArray())) {
                $orderObj->status = 1;
                $orderObj->save();

                //修改工单列表关联表数据状态
                $type = 1;
                $relateId = $orderObj->id;
                $status = 1;
                OrderEngine::changeOrderListRelationStatus($type, $relateId, $status);
            } else {
                return [
                    'code' => 1,
                    'message' => '参数错误'
                ];
            }
        }

        //更新管理员消息状态为3已分配待开工(需原状态为2需分配)
        $typeUserId = $orderProcess->uid;
        $typeId = $orderProcess->id;
        UserMessage::updateTypeStatusByTypeId(2, $typeId, $typeUserId, 3);

        return [
            'code' => 0,
            'message' => '分派成功'
        ];
    }


    //分派用户工单详情页面(厂长接单页面)
    public function getOrderDetailAssignment(Request $request)
    {
    }

    //查看被分配员工信息页面（工序管理员查看接单员工详情页面）
    public function getOrderDetailCourseAssignment()
    {
        //获取基础参数
        $orderProcessCourseId = request('order_process_course_id');
        if (!$orderProcessCourseId) {
            return [
                'code' => 1,
                'msg' => '参数错误'
            ];
        }
        //获取员工工单信息
        $orderProcessCourseRow = OrderProcessCourse::where(['id' => $orderProcessCourseId])->first()->toArray();
        //获取工序工单信息
        $orderProcessRow = OrderProcess::where(['id' => $orderProcessCourseRow['order_process_id']])->first()->toArray();
        //获取工单信息
        $orderRow = Order::where(['id' => $orderProcessRow['order_id']])->first()->toArray();


        //处理图片数据
        $imgIdList = explode(',', $orderRow['production_case_diagram']);
        $exampleImg = '';
        foreach ($imgIdList as $imgId) {
            if (!trim($imgId)) {//过滤空格 图片id应该不会有0
                continue;
            }
            if (!$exampleImg) {//取第一张图作为示例图
                $exampleImg = ImgUpload::getImgUrlById($imgId);
            }
        }

        //获取工单对应的所有工序
        $orderProcessList = OrderType::getAllOrderTypeProcess($orderRow['order_type'])->toArray();
        $blueColor = '#00AAEE';
        $greColor = '#B5B5B5';
        $androidBgBlue = 'bluecircle.png';
        $androidBgGrey = 'graycircle.png';

        $tabviewSource = [];//对应页面上纵向列表
        $tabviewSource[] = [
            'idName' => 27,
            '$littleTimeValue' => !empty($orderProcessCourseRow['created_at']) ? date('H:i', $orderProcessCourseRow['created_at']) : '',
            '$otherTimeValue' => !empty($orderProcessCourseRow['created_at']) ? date('Y-m-d', $orderProcessCourseRow['created_at']) : '',
            '$seeDetaileFunctionName' => '',
            '$departmentManageValue' => '已下单，待处理',
            '$userManageValue' => '',
            '$workMachineValue' => '',
            '$lookDetaileButtonHiden' => 1,
            '$userManageHiden' => 1,
            '$workMachineHiden' => 1,
            '$planTimeValue' => '',
            '$planTimeHiden' => 1
        ];


        $list = [];//对应页面上横向列表
        $list[] = [
            '$statusValue' => '',
            '$departmentValue' => '待开工',
            '$leftHiden' => 1,
            '$rightHiden' => 0,
            '$statusHiden' => 1,
            '$departmentFontColor' => $blueColor,
            '$statusViewBG' => $blueColor,
            '$statusViewBorderColor' => $blueColor,
            '$androidBg' => $androidBgBlue
        ];//默认自带条目

        //通过工单不同状态展示不同页面
        if ($orderProcessCourseRow['status'] == 1) {//待接单状态
            ////横向进度栏
            //生产中进度栏
            $list[] = [
                '$statusValue' => '',
                '$departmentValue' => '生产中',
                '$leftHiden' => 0,
                '$rightHiden' => 0,
                '$statusHiden' => 1,
                '$departmentFontColor' => $greColor,
                '$statusViewBG' => $greColor,
                '$statusViewBorderColor' => $greColor,
                '$androidBg' => $androidBgGrey
            ];

            //已完成进度栏
            $list[] = [
                '$statusValue' => '',
                '$departmentValue' => '已完成',
                '$leftHiden' => 0,
                '$rightHiden' => 1,
                '$statusHiden' => 1,
                '$departmentFontColor' => $greColor,
                '$statusViewBG' => $greColor,
                '$statusViewBorderColor' => $greColor,
                '$androidBg' => $androidBgGrey
            ];

            /////纵向状态栏
            //预估时间
            $estimatedTime = $orderProcessCourseRow['start_time'] + $orderProcessCourseRow['estimated_time_hour'] * 3600 + $orderProcessCourseRow['estimated_time_minute'] * 60;
            //处理人信息
            $userInfo = DepartmentUser::getCurrentInfo($orderProcessCourseRow['uid'])->toArray();

            ////简单版取消领材阶段
//            $tabviewSource[] = [
//                'idName' => 27,
//                '$littleTimeValue' => date('H:i', $orderProcessCourseRow['receive_material_time']),
//                '$otherTimeValue' => date('Y-m-d', $orderProcessCourseRow['receive_material_time']),
//                '$seeDetaileFunctionName' => '',
//                '$departmentManageValue' => '已领材',
//                '$userManageValue' => '',
//                '$workMachineValue' => '',
//                '$lookDetaileButtonHiden' => 1,
//                '$userManageHiden' => 1,
//                '$workMachineHiden' => 1,
//                '$planTimeValue' => '',
//                '$planTimeHiden' => 1
//            ];
            //待接单状态无信息--已调整
        } elseif ($orderProcessCourseRow['status'] == 2) {//确认开工-未领取材料 调整：未领取材料待开工
            ////横向进度栏
            //生产中进度栏
            $list[] = [
                '$statusValue' => '',
                '$departmentValue' => '生产中',
                '$leftHiden' => 0,
                '$rightHiden' => 0,
                '$statusHiden' => 1,
                '$departmentFontColor' => $greColor,
                '$statusViewBG' => $greColor,
                '$statusViewBorderColor' => $greColor,
                '$androidBg' => $androidBgGrey
            ];

            //已完成进度栏
            $list[] = [
                '$statusValue' => '',
                '$departmentValue' => '已完成',
                '$leftHiden' => 0,
                '$rightHiden' => 1,
                '$statusHiden' => 1,
                '$departmentFontColor' => $greColor,
                '$statusViewBG' => $greColor,
                '$statusViewBorderColor' => $greColor,
                '$androidBg' => $androidBgGrey
            ];

            /////纵向状态栏
//            //预估时间
//            $estimatedTime = $orderProcessCourseRow['start_time'] + $orderProcessCourseRow['estimated_time_hour'] * 3600 + $orderProcessCourseRow['estimated_time_minute'] * 60;
//            //处理人信息
//            $userInfo = DepartmentUser::getCurrentInfo($orderProcessCourseRow['uid'])->toArray();
//            $tabviewSource[] = [
//                'idName' => 27,
//                '$littleTimeValue' => date('H:i', $orderProcessCourseRow['start_time']),
//                '$otherTimeValue' => date('Y-m-d', $orderProcessCourseRow['start_time']),
//                '$seeDetaileFunctionName' => '',
//                '$departmentManageValue' => '[处理人]' . $userInfo['truename'],
//                '$userManageValue' => '',
//                '$workMachineValue' => '',
//                '$lookDetaileButtonHiden' => 1,
//                '$userManageHiden' => 1,
//                '$workMachineHiden' => 1,
//                '$planTimeValue' => '预计完成时间：' . date('Y年m月d日 H时', $estimatedTime),
//                '$planTimeHiden' => 0
//            ];
        } elseif ($orderProcessCourseRow['status'] == 3) {//已领取材料
            ////横向进度栏
            //生产中进度栏
            $list[] = [
                '$statusValue' => '',
                '$departmentValue' => '生产中',
                '$leftHiden' => 0,
                '$rightHiden' => 0,
                '$statusHiden' => 1,
                '$departmentFontColor' => $blueColor,
                '$statusViewBG' => $blueColor,
                '$statusViewBorderColor' => $blueColor,
                '$androidBg' => $androidBgBlue
            ];

            //已完成进度栏
            $list[] = [
                '$statusValue' => '',
                '$departmentValue' => '已完成',
                '$leftHiden' => 0,
                '$rightHiden' => 1,
                '$statusHiden' => 1,
                '$departmentFontColor' => $greColor,
                '$statusViewBG' => $greColor,
                '$statusViewBorderColor' => $greColor,
                '$androidBg' => $androidBgGrey
            ];

            /////纵向状态栏
            //预估时间
            $estimatedTime = $orderProcessCourseRow['start_time'] + $orderProcessCourseRow['estimated_time_hour'] * 3600 + $orderProcessCourseRow['estimated_time_minute'] * 60;

            if ($estimatedTime < 631152000) {//过滤1970的情况
                $planTimeValue = '';
            } else {
                $planTimeValue = '预计完成时间：' . date('Y年m月d日 H时', $estimatedTime);
            }


            //处理人信息
            $userInfo = DepartmentUser::getCurrentInfo($orderProcessCourseRow['uid'])->toArray();

            ////简单版取消领材阶段
//            $tabviewSource[] = [
//                'idName' => 27,
//                '$littleTimeValue' => date('H:i', $orderProcessCourseRow['receive_material_time']),
//                '$otherTimeValue' => date('Y-m-d', $orderProcessCourseRow['receive_material_time']),
//                '$seeDetaileFunctionName' => '',
//                '$departmentManageValue' => '已领材',
//                '$userManageValue' => '',
//                '$workMachineValue' => '',
//                '$lookDetaileButtonHiden' => 1,
//                '$userManageHiden' => 1,
//                '$workMachineHiden' => 1,
//                '$planTimeValue' => '',
//                '$planTimeHiden' => 1
//            ];

            //如果没有开始时间就不展示
            if ($orderProcessCourseRow['start_time']) {
                $tabviewSource[] = [
                    'idName' => 27,
                    '$littleTimeValue' => !empty($orderProcessCourseRow['start_time']) ? date('H:i', $orderProcessCourseRow['start_time']) : '',
                    '$otherTimeValue' => !empty($orderProcessCourseRow['start_time']) ? date('Y-m-d', $orderProcessCourseRow['start_time']) : '',

                    '$seeDetaileFunctionName' => '',
                    '$departmentManageValue' => '[处理人]' . $userInfo['truename'],
                    '$userManageValue' => '',
                    '$workMachineValue' => '',
                    '$lookDetaileButtonHiden' => 1,
                    '$userManageHiden' => 1,
                    '$workMachineHiden' => 1,
                    '$planTimeValue' => $planTimeValue,
                    '$planTimeHiden' => 0
                ];
            }

        } elseif ($orderProcessCourseRow['status'] == 4) {//确认完工
            ////横向进度栏
            //生产中进度栏
            $list[] = [
                '$statusValue' => '',
                '$departmentValue' => '生产中',
                '$leftHiden' => 0,
                '$rightHiden' => 0,
                '$statusHiden' => 1,
                '$departmentFontColor' => $blueColor,
                '$statusViewBG' => $blueColor,
                '$statusViewBorderColor' => $blueColor,
                '$androidBg' => $androidBgBlue
            ];

            //已完成进度栏
            $list[] = [
                '$statusValue' => '',
                '$departmentValue' => '已完成',
                '$leftHiden' => 0,
                '$rightHiden' => 1,
                '$statusHiden' => 1,
                '$departmentFontColor' => $blueColor,
                '$statusViewBG' => $blueColor,
                '$statusViewBorderColor' => $blueColor,
                '$androidBg' => $androidBgBlue
            ];

            /////纵向状态栏
            //预估时间
            $estimatedTime = $orderProcessCourseRow['start_time'] + $orderProcessCourseRow['estimated_time_hour'] * 3600 + $orderProcessCourseRow['estimated_time_minute'] * 60;


            if ($estimatedTime < 631152000) {//过滤1970的情况
                $planTimeValue = '';
            } else {
                $planTimeValue = '预计完成时间：' . date('Y年m月d日 H时', $estimatedTime);
            }

            //处理人信息
            $userInfo = DepartmentUser::getCurrentInfo($orderProcessCourseRow['uid'])->toArray();

            ////简单版取消领材阶段
//            $tabviewSource[] = [
//                'idName' => 27,
//                '$littleTimeValue' => date('H:i', $orderProcessCourseRow['receive_material_time']),
//                '$otherTimeValue' => date('Y-m-d', $orderProcessCourseRow['receive_material_time']),
//                '$seeDetaileFunctionName' => '',
//                '$departmentManageValue' => '已领材',
//                '$userManageValue' => '',
//                '$workMachineValue' => '',
//                '$lookDetaileButtonHiden' => 1,
//                '$userManageHiden' => 1,
//                '$workMachineHiden' => 1,
//                '$planTimeValue' => '',
//                '$planTimeHiden' => 1
//            ];

            //如果没有开始时间就不展示
            if ($orderProcessCourseRow['start_time']) {
                $tabviewSource[] = [
                    'idName' => 27,
                    '$littleTimeValue' => date('H:i', $orderProcessCourseRow['start_time']),
                    '$otherTimeValue' => date('Y-m-d', $orderProcessCourseRow['start_time']),
                    '$seeDetaileFunctionName' => '',
                    '$departmentManageValue' => '[处理人]' . $userInfo['truename'],
                    '$userManageValue' => '',
                    '$workMachineValue' => '',
                    '$lookDetaileButtonHiden' => 1,
                    '$userManageHiden' => 1,
                    '$workMachineHiden' => 1,
                    '$planTimeValue' => $planTimeValue,
                    '$planTimeHiden' => 0
                ];
            }

            $tabviewSource[] = [
                'idName' => 27,
                '$littleTimeValue' => date('H:i', $orderProcessCourseRow['updated_at']),
                '$otherTimeValue' => date('Y-m-d', $orderProcessCourseRow['updated_at']),
                '$seeDetaileFunctionName' => '',
                '$departmentManageValue' => '已完成',
                '$userManageValue' => '',
                '$workMachineValue' => '',
                '$lookDetaileButtonHiden' => 1,
                '$userManageHiden' => 1,
                '$workMachineHiden' => 1,
                '$planTimeValue' => '',
                '$planTimeHiden' => 1
            ];

        } else {
            return [
                'code' => 1,
                'msg' => '员工工单状态异常'
            ];
        }

//        $tabviewSource = array_reverse($tabviewSource);
        //获取工序对应的详细信息
        $productName = \App\Engine\OrderEngine::getOrderFiledValueTrue($orderRow['product_name'], 20);
        $returnApe = [
            'pageID' => 14,
            'data' => [
                '$productImage' => $exampleImg,
                '$productNameValue' => $productName,
                '$productOrderValue' => '生产单号:' . $orderRow['order_title'],
                '$imageClickFunctionName' => 'imageClickAction' . $orderRow['id'],
                '$lookOrderDetaileFunctionName' => 'lookOrderDetaile' . $orderRow['id'],
                '$tabviewSource' => $tabviewSource,
                '$list' => $list
            ]
        ];
        return $returnApe;
    }

    //工单各类型数量接口
    public function getOrderAllTypeNum()
    {
        $userId = Func::getHeaderValueByName('userid');
        $userInfo = DepartmentUser::getCurrentInfo($userId)->toArray();
        $companyId = isset($userInfo['company_id']) ? $userInfo['company_id'] : '';

        //附加功能，将不预期保留的草稿箱数据删除 调整，只删除10分钟前的数据
        $allDeleteTime = time() - 60 * 10;
        $where = [
            ['company_id', '=', $companyId],
            ['uid', '=', $userId],
            ['is_trash', '=', 1],
            ['created_at', '<', $allDeleteTime]
        ];
        OrderPre::where($where)->delete();


        //待派单数量
        $noAssignOrdderNum = Order::where(['company_id' => $companyId, 'status' => 4, 'uid' => $userId])->get()->count();

        //已派单数量
        $isAssignOrdderNum = Order::where(['company_id' => $companyId, 'uid' => $userId])->where('status', '!=', '4')->get()->count();

        //草稿箱数量
        $draftOrderNum = OrderPre::where(['company_id' => $companyId, 'uid' => $userId])->get()->count();

        return [
            'no_assign_ordder_num' => $noAssignOrdderNum,//待派单数量
            'is_assign_ordder_num' => $isAssignOrdderNum,//已派单数量
            'draft_order_num' => $draftOrderNum,//草稿箱数量
        ];
    }

    //工单详情新接口-未完工
    public function getOrderDetailNewNoComplete(Request $request)
    {
        //获取传入数据
        $input = $request->all();
        $input['order_process_id'] = isset($input['order_process_id']) ? $input['order_process_id'] : '';//工序工单id
        $input['order_process_course_id'] = isset($input['order_process_course_id']) ? $input['order_process_course_id'] : '';//员工id

        $userId = Func::getHeaderValueByName('userid');
        $userInfo = DepartmentUser::getCurrentInfo($userId)->toArray();
        $companyId = $userInfo['company_id'];

        //逻辑调整传入的id实际为员工工单id
        if ($input['order_process_course_id']) {
            $orderProcessCourseId = $input['order_process_course_id'];
            $orderProcessCourseRow = OrderProcessCourse::where(['id' => $orderProcessCourseId])->first()->toArray();
            $orderProcessId = $orderProcessCourseRow['order_process_id'];
            $input['order_process_id'] = $orderProcessCourseId;
        } else {
            $orderProcessId = $input['order_process_id'];
        }

        //校验参数
        $rules = [
            'order_process_id' => 'required',
        ];
        $messages = [
            'order_process_id.required' => '缺少工单id',
        ];
        $this->validateRequestParameters($input, $rules, true, $messages);


        //获取对应工单工序表信息
        $orderProcessInfo = OrderProcess::where('id', $orderProcessId)->first()->toArray();
        //获取工单信息
        $orderInfo = Order::where('id', $orderProcessInfo['order_id'])->first()->toArray();
        //获取工序名称
        $processTitle = Process::getOneValueById($orderProcessInfo['process_type'], 'title');

        $processFieldList = Process::getFieldListByProcessId($orderProcessInfo['process_type']);

        $dataList = [];
        $dataList[] = [
            'title' => '工单号',
            'value' => $orderInfo['order_title'],
        ];
        foreach ($processFieldList as $processFieldRow) {
            if ($processFieldRow['field_name'] == 'remark') {//备注另外处理
                continue;
            }

            //通过字段类型不同处理
            //获取字段对应的类型1=>'文本',2=>'文本域',3=>'下拉框-跳界面',4=>'跳材料',5=>'有单位',6=>'开关',7=>'时间'
            $tmpFiledType = ProcessField::getFieldTypeByFieldName($processFieldRow['field_name'], $companyId);
            $showTitle = $orderProcessInfo[$processFieldRow['field_name']];//默认展示字段的内容
            if ($tmpFiledType == 5) {//有单位 数量+单位
                if ($orderProcessInfo[$processFieldRow['field_name']]) {
                    $tmpArr = explode(',', $orderProcessInfo[$processFieldRow['field_name']]);
                    $showNum = $tmpArr[0];
                    if (isset($tmpArr[1])) {
                        $unitId = $tmpArr[1];
                    } else {
                        $unitId = '';
                    }
                    $showTitle = $showNum . ' ' . $unitId;
                } else {
                    $showTitle = '';
                }
            } elseif ($tmpFiledType == 6) {//开关
                $showTitle = $orderProcessInfo[$processFieldRow['field_name']] ? '是' : '否';
            } elseif ($tmpFiledType == 4) {//材料选择
                continue;
            }

            if ($processFieldRow['field_name'] == 'completed_number') {//未完工时不显示完工数量
                continue;
            }

            $dataList[] = [
                'title' => $processFieldRow['title'],
                'value' => $showTitle,
            ];
        }

        //材料领取
        $materialList = [];
        if (!$input['order_process_course_id']) {//管理员或其他角色进入，查看工序工单整体情况
            //获取所有员工的领取材料情况
            $orderProcessCourseList = OrderProcessCourse::where(['order_process_id' => $orderProcessInfo['id']])->get()->toArray();
            $orderPorcessCourseIds = [];
            foreach ($orderProcessCourseList as $orderProcessCourseRow) {
                $orderPorcessCourseIds[] = $orderProcessCourseRow['id'];
            }

            $orderMaterialArr = OrderMaterialCourse::where(['process_type' => $orderProcessInfo['process_type']])->whereIn('order_process_course_id', $orderPorcessCourseIds)->get()->toArray();

            $orderMaterialListTmp = [];
            foreach ($orderMaterialArr as $orderMaterialRow) {
                if (isset($orderMaterialListTmp[$orderMaterialRow['material_id']])) {
                    $orderMaterialListTmp[$orderMaterialRow['material_id']]['receive_number'] += $orderMaterialRow['receive_number'];
                    $orderMaterialListTmp[$orderMaterialRow['material_id']]['residual_number'] += $orderMaterialRow['residual_number'];
                    $orderMaterialListTmp[$orderMaterialRow['material_id']]['scrap_number'] += $orderMaterialRow['scrap_number'];
                } else {
                    $orderMaterialListTmp[$orderMaterialRow['material_id']] = $orderMaterialRow;
                }
            }

            $orderMaterialList = [];
            foreach ($orderMaterialListTmp as $orderMaterialRow) {
                $orderMaterialList[] = $orderMaterialRow;
            }
        } else {//员工进入,查看单员工情况
            $orderMaterialList = OrderMaterialCourse::where(['order_process_course_id' => $orderProcessCourseId, 'process_type' => $orderProcessInfo['process_type']])->get()->toArray();
        }

        foreach ($orderMaterialList as $orderMaterialRow) {
            $materialRow = ProductEngine::getProductInfo($orderMaterialRow['material_id']);
            $materialList[] = [
                'material_id' => $materialRow['id'],//材料id
                'product_name' => $materialRow['product_name'],//材料名称
                'product_no' => $materialRow['product_no'],//材料编号
                'receive_number' => $orderMaterialRow['receive_number'],//领取数量
            ];
        }

        return [
            'title' => $processTitle,
            'dataList' => $dataList,
            'remark' => $orderProcessInfo['remark'],
            'materialList' => $materialList,
        ];
    }

    //工单详情新接口-已完工
    public function getOrderDetailNewComplete(Request $request)
    {
        //获取传入数据
        $input = $request->all();
        $input['order_process_id'] = isset($input['order_process_id']) ? $input['order_process_id'] : '';//工序工单id
        $input['order_process_course_id'] = isset($input['order_process_course_id']) ? $input['order_process_course_id'] : '';//员工id

        $userId = Func::getHeaderValueByName('userid');
        $userInfo = DepartmentUser::getCurrentInfo($userId)->toArray();
        $companyId = $userInfo['company_id'];

        //逻辑调整传入的id实际为员工工单id
        if ($input['order_process_course_id']) {
            $orderProcessCourseId = $input['order_process_course_id'];
            $orderProcessCourseRow = OrderProcessCourse::where(['id' => $orderProcessCourseId])->first()->toArray();
            $orderProcessId = $orderProcessCourseRow['order_process_id'];
            $input['order_process_id'] = $orderProcessCourseId;
        } else {
            $orderProcessId = $input['order_process_id'];
        }

        //校验参数
        $rules = [
            'order_process_id' => 'required',
        ];
        $messages = [
            'order_process_id.required' => '缺少工单id',
        ];
        $this->validateRequestParameters($input, $rules, true, $messages);


        //获取对应工单工序表信息
        $orderProcessInfo = OrderProcess::where('id', $orderProcessId)->first()->toArray();
        //获取工单信息
        $orderInfo = Order::where('id', $orderProcessInfo['order_id'])->first()->toArray();
        //获取工序名称
        $processTitle = Process::getOneValueById($orderProcessInfo['process_type'], 'title');

        $processFieldList = Process::getFieldListByProcessId($orderProcessInfo['process_type']);

        $dataList = [];
        foreach ($processFieldList as $processFieldRow) {
            if ($processFieldRow['field_name'] == 'remark') {//备注另外处理
                continue;
            }

            //通过字段类型不同处理
            //获取字段对应的类型1=>'文本',2=>'文本域',3=>'下拉框-跳界面',4=>'跳材料',5=>'有单位',6=>'开关',7=>'时间'
            $tmpFiledType = ProcessField::getFieldTypeByFieldName($processFieldRow['field_name'], $companyId);
            $showTitle = $orderProcessInfo[$processFieldRow['field_name']];//默认展示字段的内容
            if ($tmpFiledType == 5) {//有单位 数量+单位
                if ($orderProcessInfo[$processFieldRow['field_name']]) {
                    $tmpArr = explode(',', $orderProcessInfo[$processFieldRow['field_name']]);
                    $showNum = $tmpArr[0];
                    if (isset($tmpArr[1])) {
                        $unitId = $tmpArr[1];
                    } else {
                        $unitId = '';
                    }
                    $showTitle = $showNum . ' ' . $unitId;
                } else {
                    $showTitle = '';
                }
            } elseif ($tmpFiledType == 6) {//开关
                $showTitle = $orderProcessInfo[$processFieldRow['field_name']] ? '是' : '否';
            } elseif ($tmpFiledType == 4) {//材料选择
                continue;
            }

            if ($input['order_process_course_id']) {//员工查看分配自己
                if ($processFieldRow['field_name'] == 'completed_number') {//需完成数量，员工使用被分配的数量
                    $showTitle = $orderProcessCourseRow['total_number'];
                }
            }

            $dataList[] = [
                'title' => $processFieldRow['title'],
                'value' => $showTitle,
            ];
        }

        //材料领取
        $materialList = [];
        $meterCounterImgList = [];//计米器图片列表
        if (!$input['order_process_course_id']) {//管理员或其他角色进入，查看工序工单整体情况
            //获取所有员工的领取材料情况
            $orderProcessCourseList = OrderProcessCourse::where(['order_process_id' => $orderProcessInfo['id']])->get()->toArray();
            $orderPorcessCourseIds = [];
            $finishNum = 0;//已完成数量
            $wasteNum = 0;//废品数量
            foreach ($orderProcessCourseList as $orderProcessCourseRow) {
                $orderPorcessCourseIds[] = $orderProcessCourseRow['id'];
                $finishNum += $orderProcessCourseRow['finish_number'];
                $wasteNum += $orderProcessCourseRow['waste_number'];

                //记录计米器图片
                if ($orderProcessCourseRow['meter_counter']) {
                    $meterCounterImg = ImgUpload::getImgUrlById($orderProcessCourseRow['meter_counter']);
                    if ($meterCounterImg) {
                        $meterCounterImgList[] = $meterCounterImg;
                    }
                }
            }

            $orderMaterialArr = OrderMaterialCourse::where(['process_type' => $orderProcessInfo['process_type']])->whereIn('order_process_course_id', $orderPorcessCourseIds)->get()->toArray();

            $orderMaterialListTmp = [];
            foreach ($orderMaterialArr as $orderMaterialRow) {
                if (isset($orderMaterialListTmp[$orderMaterialRow['material_id']])) {
                    $orderMaterialListTmp[$orderMaterialRow['material_id']]['receive_number'] += $orderMaterialRow['receive_number'];
                    $orderMaterialListTmp[$orderMaterialRow['material_id']]['residual_number'] += $orderMaterialRow['residual_number'];
                    $orderMaterialListTmp[$orderMaterialRow['material_id']]['scrap_number'] += $orderMaterialRow['scrap_number'];
                } else {
                    $orderMaterialListTmp[$orderMaterialRow['material_id']] = $orderMaterialRow;
                }
            }

            $orderMaterialList = [];
            foreach ($orderMaterialListTmp as $orderMaterialRow) {
                $orderMaterialList[] = $orderMaterialRow;
            }
        } else {//员工进入,查看单员工情况
            $orderMaterialList = OrderMaterialCourse::where(['order_process_course_id' => $orderProcessCourseId, 'process_type' => $orderProcessInfo['process_type']])->get()->toArray();
            $finishNum = $orderProcessCourseRow['finish_number'];//已完成数量
            $wasteNum = $orderProcessCourseRow['waste_number'] ? $orderProcessCourseRow['waste_number'] : 0;//过滤null

            //记录计米器图片
            if ($orderProcessCourseRow['meter_counter']) {
                $meterCounterImg = ImgUpload::getImgUrlById($orderProcessCourseRow['meter_counter']);
                if ($meterCounterImg) {
                    $meterCounterImgList[] = $meterCounterImg;
                }
            }
        }

        foreach ($orderMaterialList as $orderMaterialRow) {
            //获取材料信息
            $materialRow = ProductEngine::getProductInfo($orderMaterialRow['material_id']);
            //废品率
            $userNum = $orderMaterialRow['receive_number'] - $orderMaterialRow['residual_number'];
            if ($userNum) {
                $rejectRate = (round($orderMaterialRow['scrap_number'] / $userNum * 100, 4)) . '%';
            } else {
                $rejectRate = 0;
            }

            $materialList[] = [
                'material_id' => $materialRow['id'],//材料id
                'product_name' => $materialRow['product_name'],//材料名称
                'product_no' => $materialRow['product_no'],//材料编号
                'unit' => $materialRow['unit'],//材料单位
                //图片
                //库存
                //
                'receive_number' => $orderMaterialRow['receive_number'],//领取数量
                'residual_number' => $orderMaterialRow['residual_number'],//余品数量
                'scrap_number' => $orderMaterialRow['scrap_number'],//废品数量
                'rejectRate' => $rejectRate,//废品率
            ];
        }

        //计算成品废品率
        if ($finishNum + $wasteNum != 0) {
            $wasteRate = (round(($wasteNum / ($finishNum + $wasteNum)), 4) * 100) . '%';
        } else {
            $wasteRate = '';
        }


        return [
            'title' => $processTitle,
            'dataList' => $dataList,
            'remark' => $orderProcessInfo['remark'],
            'materialList' => $materialList,
            'meterCounterImgList' => $meterCounterImgList,
            'finishNum' => $finishNum,
            'wasteNum' => $wasteNum,
            'wasteRate' => $wasteRate,
        ];
    }

    //下单人工单分配类型
    public function getOrderManageAssignmentType()
    {
        $orderId = request('order_id', '');

        $userId = Func::getHeaderValueByName('userid');
        $userInfo = DepartmentUser::getCurrentInfo($userId)->toArray();
        $companyId = isset($userInfo['company_id']) ? $userInfo['company_id'] : '';

        //获取工单信息
        $orderInfo = Order::where('id', $orderId)->first()->toArray();
        $orderTypeId = $orderInfo['order_type'];

        $result = OrderType::getAllStepsWithDistribution($orderTypeId);
        //获取工序可分派给工序管理员的列表
        $result->transform(function ($item) {
//            $item->distributionUser = Privilege::getWithDepartmentUser( $item->distribution );
            $distributionUser = DepartmentUser::getWithPrivilege($item->distribution);
            $process_id = $item->process_id;
            $distributionUser->transform(function ($item) use ($process_id) {
                $item->process_id = $process_id;
                $item->ygtUser->avatar = $item->ygtUser->avatar ? Func::getImgUrlById($item->ygtUser->avatar) : asset('upload/appicon/logo.png');
                return $item;
            });
            $item->distributionUser = $distributionUser->toArray();
            return $item;
        });

        //判断工单类型对应的工序里是否有设置工序管理员
        $needAssignmentProcess = false;//需要工序分派
        foreach ($result as $tmpValue) {
            if (!empty($tmpValue['distributionUser'])) {
                $needAssignmentProcess = true;
            }
        }


        if ($needAssignmentProcess) {
            //如果已经派发了工序管理员（中途退出了，直接进入派发工序管理员页面）
            $isAllAssign = 1;//是否都已经派发
            $orderProcessList = OrderProcess::where(['order_id' => $orderId])->get()->toArray();
            foreach ($orderProcessList as $orderProcessRow) {
                if (!$orderProcessRow['uid']) {
                    $isAllAssign = 0;
                }
            }

            if ($isAllAssign) {
                return [
                    'type' => 4,//直接派发工单给员工
                    'order_type' => $orderTypeId,//订单类型id
                ];
            }

            return [
                'type' => 1,//正常流程
                'order_type' => $orderTypeId,//正常流程
            ];


        } else {
            //先分配工单给自己
            $orderProcessCollectionList = OrderProcess::where(['order_id' => $orderId])->get();
            foreach ($orderProcessCollectionList as $orderProcessCollection) {
                $orderProcessCollection->uid = $userId;
                $orderProcessCollection->save();

                //存入工单列表关联表
                OrderEngine::importProcessManagerOrder($orderProcessCollection->toArray());
            }

            ////调整-所有工序的订单一次性分派完成 20180208 | 调整-不再直接分派给员工，需要下单人分派给指定员工

            return [
                'type' => 4,//直接派发工单给员工
                'order_type' => $orderTypeId,//订单类型id
            ];


            //第一个工序分派给员工
//            $processFirstList = OrderType::getFirstProcessBag($orderTypeId)->toArray();
//            $processFirstList = OrderType::getAllOrderTypeProcess($orderTypeId)->toArray();
//            foreach ($processFirstList as $processId) {
//                $orderProcessRow = OrderProcess::where(['order_id' => $orderId, 'process_type' => $processId])->first();
//                $processId = $orderProcessRow['process_type'];
//                //获取有提交权限的角色id
//                $privilegeIds = PermissionEngine::getStepActionPrivilegeIdsByOrderTypeProcess($orderTypeId, $processId, 4); //1:查看;2:可写;3:分配;4:提交;5:转发;
//                //获取角色下的用户id
//                $userList = DepartmentUser::getWithPrivilege($privilegeIds);
//
//                //给此步骤有查看权限的人发消息
//                $processId = $orderProcessRow['process_type'];
//                $orderTypeId = $orderInfo['order_type'];
//                $privilegeIds = PermissionEngine::getStepActionPrivilegeIdsByOrderTypeProcess($orderTypeId, $processId, 1);//1:查看;2:可写;3:分配;4:提交;5:转发;
//
//                //存入工单列表关联表
//                OrderEngine::importProcessSeeOrder($orderProcessRow->toArray(), $privilegeIds);
//
//                $userRow = DepartmentUser::getCurrentInfo($orderInfo['uid'])->toArray();
//
//                foreach ($userList as $tmpUserRow) {
//                    $tmpUid = $tmpUserRow['user_id'];
//
//                    $orderProcessCourseObj = OrderProcessCourse::firstOrNew(['order_process_id' => $orderProcessRow['id'], 'uid' => $tmpUid]);
//                    $tmpInsertRow = [
//                        'uid' => $tmpUid,
//                        'total_number' => 0,//自动分派，需完成数量默认为0
//                        'order_process_id' => $orderProcessRow['id'],
//                        'assign_id' => $userId,//派发人id
////                        'status' => 2,//状态 1-待接单 调整为先领取材料 2-待领取材料
//                        'status' => 1,//状态 1-待接单 调整为先领取材料 2-待领取材料 临时调整-跳过领材阶段
//                        'company_id' => $companyId,//企业Id
//                    ];
//                    $orderProcessCourseObj->fill($tmpInsertRow);
//                    $orderProcessCourseObj->save();
//                    $orderPorcessCourseId = $orderProcessCourseObj->id;
//
//                    //存入工单列表关联表
//                    OrderEngine::importProcessCourseOrder($orderProcessCourseObj->toArray());
//                }
//
//                //调整：无工序管理员订单，员工开工后再修改工序订单状态
////                //修改工序工单状态为2（已接单）
////                $orderProcessRow->status = 2;
////                $orderProcessRow->save();
//
//                //修改工单状态
//                $orderObj = Order::where(['id' => $orderId])->first();
//                if (!empty($orderObj->toArray())) {
//                    $orderObj->status = 1;
//                    $orderObj->save();
//
//                    //修改工单列表关联表数据状态
//                    $type = 1;
//                    $relateId = $orderObj->id;
//                    $status = 1;
//                    OrderEngine::changeOrderListRelationStatus($type, $relateId, $status);
//                } else {
//                    return [
//                        'code' => 1,
//                        'message' => '参数错误'
//                    ];
//                }
//            }

//            return [
//                'type' => 3,
//                'message' => '分派成功'
//            ];
        }
    }

    //主工单工单详情-新接口
    public function getManagerOrderDetailListNew(Request $request)
    {
        //获取传入数据
        $input = $request->all();
        $input['order_id'] = isset($input['order_id']) ? $input['order_id'] : '';//工单-id
        $input['customer_order_flag'] = isset($input['customer_order_flag']) ? $input['customer_order_flag'] : '';//纯查看界面

        //获取工单信息
        $orderInfo = Order::where('id', $input['order_id'])->first()->toArray();

        //工单基础信息字段，目前格式固定 -- 已调整为后台控制 20180131
        $userId = Func::getHeaderValueByName('userid');
        $userInfo = DepartmentUser::getCurrentInfo($userId)->toArray();
        $companyId = isset($userInfo['company_id']) ? $userInfo['company_id'] : '';
        $orderBaseFieldList = OrderFieldCompany::getActiveFieldList($companyId);

        $listAll = [];
        $baseInfoList = [];
        //基本信息先固定

        $imageList = [];
        if ($orderInfo['production_case_diagram']) {
            $imageIdList = explode(',', $orderInfo['production_case_diagram']);
            foreach ($imageIdList as $imageId) {
                $imageUrl = ImgUpload::getImgUrlById($imageId, true, false);
                $imageList[] = $imageUrl;
            }
        }
        $customerAddressArr = [];
        $buyersInvoiceId = '';
        $textArr = [];
        foreach ($orderBaseFieldList as $key => $row) {
            $leftLabelValue = $row['title'];
            $rightLabelValue = $orderInfo[$row['field_name']];
            if ($row['field_type'] == 9) {//图片处理
                //如果有上传的图片地址，存入数组中
                continue;//另外处理
            } elseif ($row['field_type'] == 8) {//配送地址 处理
                //continue;//另外处理
                $addressWhere = ['id' => $rightLabelValue];
//                $customerAddress = CustomerAddress::getInfo($addressWhere);
                $customerAddress = \App\Eloquent\Ygt\BuyersAddress::withTrashed()->where($addressWhere)->first();

                if ($customerAddress) {
                    $customerAddressArr = $customerAddress->toArray();
                }
                continue;
            } elseif ($row['field_type'] == 21) {//开票资料另外处理
                $buyersInvoiceId = $orderInfo[$row['field_name']];
                continue;
            }elseif ($row['field_type'] == 2) {//文本域类型的字段另外处理
                $rightLabelValue = OrderEngine::getOrderFiledValueTrue($orderInfo[$row['field_name']], $row['field_type']);
                $textArr[] = [
                    'leftLabelValue' => $leftLabelValue,
                    'rightLabelValue' => $rightLabelValue
                ];
                continue;
            }


            $rightLabelValue = OrderEngine::getOrderFiledValueTrue($orderInfo[$row['field_name']], $row['field_type']);

            $baseInfoList[] = [
                'leftLabelValue' => $leftLabelValue,
                'rightLabelValue' => $rightLabelValue
            ];
        }
        //追加配送地址
//        $orderDistributionRow = OrderDistribution::where(['order_id' => $input['order_id']])->first();
//        if (!empty($orderDistributionRow)) {
//            $baseInfoList[] = [
//                'leftLabelValue' => '收货人',
//                'rightLabelValue' => $orderDistributionRow['consignee']
//            ];
//            $baseInfoList[] = [
//                'leftLabelValue' => '联系手机',
//                'rightLabelValue' => $orderDistributionRow['phone']
//            ];
//            $baseInfoList[] = [
//                'leftLabelValue' => '区县地址',
//                'rightLabelValue' => $orderDistributionRow['province_name'] . ' ' . $orderDistributionRow['city_name'] . ' ' . $orderDistributionRow['area_name']
//            ];
//            $baseInfoList[] = [
//                'leftLabelValue' => '收货人详细地址',
//                'rightLabelValue' => $orderDistributionRow['address']
//            ];
//        }
        if (!empty($customerAddressArr)) {
            $baseInfoList[] = [
                'leftLabelValue' => '收货人',
                'rightLabelValue' => $customerAddressArr['consignee']
            ];
            $baseInfoList[] = [
                'leftLabelValue' => '联系手机',
                'rightLabelValue' => $customerAddressArr['phone']
            ];
            $baseInfoList[] = [
                'leftLabelValue' => '区县地址',
                'rightLabelValue' => $customerAddressArr['province_name'] . ' ' . $customerAddressArr['city_name'] . ' ' . $customerAddressArr['area_name']
            ];
            $baseInfoList[] = [
                'leftLabelValue' => '详细地址',
                'rightLabelValue' => $customerAddressArr['address']
            ];
        }

        $isAllowUpdate = 1;
        if ($input['customer_order_flag']) {
            $isAllowUpdate = 2;
        }


        //只有下单人有权限修改工单信息 20180713 zhuyujun
        $privilegeIdList = \App\Engine\OrderEngine::getPrivilegeByNode($companyId, 1);
        if (!in_array($userInfo['privilege_id'], $privilegeIdList)) {
            $isAllowUpdate = 2;
        }


        $list1 = [];
        $customerInvoiceRow = \App\Eloquent\Ygt\BuyersInvoice::where(['id' => $buyersInvoiceId])->first();
        if ($customerInvoiceRow) {
            $list1 = [
                [
                    'leftLabelValue' => '账户名称',
                    'rightLabelValue' => $customerInvoiceRow['account_name'],
                ],
                [
                    'leftLabelValue' => '纳税人识别号',
                    'rightLabelValue' => $customerInvoiceRow['taxpayer_number'],
                ],
                [
                    'leftLabelValue' => '省市区',
                    'rightLabelValue' => $customerInvoiceRow['province_name'] . $customerInvoiceRow['city_name'] . $customerInvoiceRow['area_name'],
                ],
                [
                    'leftLabelValue' => '详细地址',
                    'rightLabelValue' => $customerInvoiceRow['address'],
                ],
                [
                    'leftLabelValue' => '电话',
                    'rightLabelValue' => $customerInvoiceRow['telphone'],
                ],
                [
                    'leftLabelValue' => '开户行',
                    'rightLabelValue' => $customerInvoiceRow['opening_bank'],
                ],
                [
                    'leftLabelValue' => '银行卡号',
                    'rightLabelValue' => $customerInvoiceRow['bank_card_number'],
                ],
            ];

        }


        $baseInfoList = array_merge($baseInfoList, $list1);
        $baseInfoList = array_merge($baseInfoList, $textArr);

        $listAll[] = [
            'titleLabelValue' => '基本信息',
            'order_id' => $orderInfo['id'],//工单id
            'is_allow_update' => $isAllowUpdate,//是否允许修改 1-允许 2-不允许
            'process_type' => 'base',//类型 base-主工单信息  process-工序工单信息
            'list' => $baseInfoList
        ];

        //动态获取工序数据
        //获取工单对应的所有工序
        $orderProcessList = OrderType::getAllOrderTypeProcess($orderInfo['order_type']);
        foreach ($orderProcessList as $processId) {
            //获取工序信息


            $orderProcessInfo = OrderProcess::where(['order_id' => $orderInfo['id'], 'process_type' => $processId])->first();
            if (!$orderProcessInfo) {
                dd(['order_id' => $orderInfo['id'], 'process_type' => $processId]);
            }


            $orderProcessInfo = OrderProcess::where(['order_id' => $orderInfo['id'], 'process_type' => $processId])->first()->toArray();
            $processTitle = Process::getOneValueById($orderProcessInfo['process_type'], 'title');
            $preProcessEstimatedTime = $orderProcessInfo['start_time'] + $orderProcessInfo['estimated_time_hour'] * 3600 + $orderProcessInfo['estimated_time_minute'] * 60;

            //工序工单状态
            $orderPorcessStautsTitleList = [
                '1' => '待接单',
                '2' => '待派发',
                '3' => '进行中',
                '4' => '已完工',
                '101' => '待开工',
            ];

            $orderPorcessStautsTitle = $orderPorcessStautsTitleList[$orderProcessInfo['status']];

            $list = [];
            //通过字段类型不同处理
            //获取字段对应的类型1=>'文本',2=>'文本域',3=>'下拉框-跳界面',4=>'跳材料',5=>'有单位',6=>'开关',7=>'时间'
            $processFieldList = Process::getFieldListByProcessId($orderProcessInfo['process_type']);
            foreach ($processFieldList as $processFieldRow) {
                $tmpFiledType = $processFieldRow['field_type'];
                $showTitle = $orderProcessInfo[$processFieldRow['field_name']];//默认展示字段的内容
                if ($tmpFiledType == 4) {//材料选择暂时不显示在
                    //显示每种材料
                    $materialIdList = explode(',', $orderProcessInfo[$processFieldRow['field_name']]);
                    foreach ($materialIdList as $materialId) {
                        if ($materialId) {
                            //获取材料信息（名称）
                            $materialObj = ProductEngine::getProductInfo($materialId);
                            $materialName = $materialId;
                            if ($materialObj) {
                                $materialName = $materialObj->product_name;
                            }

                            $list[] = [
                                'leftLabelValue' => $processFieldRow['title'],
                                'rightLabelValue' => $materialName,
                            ];
                        }
                    }
                    continue;
                }elseif($tmpFiledType == 17 && $orderProcessInfo[$processFieldRow['field_name']]){
                    $tmpCreateOrderPlateId = $orderProcessInfo[$processFieldRow['field_name']];
                    $tmpCreateOrderPlateRow = \App\Eloquent\Ygt\CreateOrderPlate::where(['id'=>$tmpCreateOrderPlateId])->first();
                    $tmpCreateOrderPlateRowContent =json_decode(htmlspecialchars_decode($tmpCreateOrderPlateRow['content']), true);
                    //显示固定版、套版组合
                    if(isset($tmpCreateOrderPlateRowContent['branch']['fixed_plate'])){
                        $tmpReList = \App\Engine\OrderEngine::getOrderPlateDealInfo($tmpCreateOrderPlateRowContent,$processFieldRow['title']);
                        foreach ($tmpReList as $tmpReRow){
                            $list[] = [
                                'leftLabelValue' => $tmpReRow['$leftLabelValue'],
                                'rightLabelValue' => $tmpReRow['$rightLabelValue'],
                            ];
                        }
                    }
                    continue;
                }elseif($tmpFiledType == 22 && $orderProcessInfo[$processFieldRow['field_name']]){
                    $tmpCreateOrderProcessProductId = $orderProcessInfo[$processFieldRow['field_name']];
                    $tmpCreateOrderProcessProductRow = \App\Eloquent\Ygt\CreateOrderProcessProduct::where(['id'=>$tmpCreateOrderProcessProductId])->first();
                    $tmpCreateOrderProcessProductRowContent =json_decode(htmlspecialchars_decode($tmpCreateOrderProcessProductRow['content']), true);
                    if($tmpCreateOrderProcessProductRowContent){
                        ///显示半成品信息
                        foreach ($tmpCreateOrderProcessProductRowContent as $tmpCreateOrderProcessProductRowContentRow){
                            $list[] = [
                                'leftLabelValue' => $processFieldRow['title'],
                                'rightLabelValue' => "【{$tmpCreateOrderProcessProductRowContentRow['number']}】{$tmpCreateOrderProcessProductRowContentRow['process_product_title']}",
                            ];
                        }
                    }
                    continue;
                }


                $showTitle = OrderEngine::getOrderFiledValueTrue($orderProcessInfo[$processFieldRow['field_name']], $tmpFiledType);

                $list[] = [
                    'leftLabelValue' => $processFieldRow['title'],
                    'rightLabelValue' => $showTitle,
                ];
            }

            $isAllowUpdate = 1;//是否允许修改
            if ($orderProcessInfo['status'] == 3 || $orderProcessInfo['status'] == 4) {//开工中或者已完工不允许修改工单
                $isAllowUpdate = 2;
            }

            if ($input['customer_order_flag']) {
                $isAllowUpdate = 2;
            }

            //只有下单人有权限修改工单信息 20180713 zhuyujun
            $privilegeIdList = \App\Engine\OrderEngine::getPrivilegeByNode($companyId, 1);
            if (!in_array($userInfo['privilege_id'], $privilegeIdList)) {
                $isAllowUpdate = 2;
            }


            //未派发的情况下显示 待派发
            if (!$orderProcessInfo['uid']) {
                $orderPorcessStautsTitle = '待派发';
            }

            $listAll[] = [
                'titleLabelValue' => $processTitle . '(' . $orderPorcessStautsTitle . ')',
                'order_process_id' => $orderProcessInfo['id'],
                'is_allow_update' => $isAllowUpdate,
                'process_type' => 'process',//类型 base-主工单信息  process-工序工单信息
                'list' => $list
            ];
        }

        $returnApe = [
            'imageList' => $imageList,
            'listAll' => $listAll
        ];
        return $returnApe;
    }


    //员工确认开工-判断是否可以开工
    public function checkConfirmStart(Request $request)
    {
        //获取传入数据
        $input = $request->all();
        $input['order_process_id'] = isset($input['order_process_id']) ? $input['order_process_id'] : '';
        $input['order_process_course_id'] = isset($input['order_process_course_id']) ? $input['order_process_course_id'] : '';//员工工单id
        $inputType = isset($input['type']) ? $input['type'] : 0;
        $inputUserId = isset($input['user_id']) ? $input['user_id'] : 0;

        //逻辑调整传入的id实际为员工工单id
        if ($input['order_process_course_id']) {
            $orderProcessCourseId = $input['order_process_course_id'];
            $orderProcessCourseRow = OrderProcessCourse::where(['id' => $orderProcessCourseId])->first()->toArray();
            $input['order_process_id'] = $orderProcessCourseRow['order_process_id'];
        }

        $userId = Func::getHeaderValueByName('userid');
//        if($inputType==1 && $inputUserId>0)
//        {
//            $userId = $inputUserId;
//        }
        $userInfo = DepartmentUser::getCurrentInfo($userId)->toArray();
        $companyId = $userInfo['company_id'];

        //校验参数
        $rules = [
            'order_process_id' => 'required',
        ];
        $messages = [
            'order_process_id.required' => '缺少工单id',
        ];
        $this->validateRequestParameters($input, $rules, true, $messages);

        //获取对应工序信息
        $orderProcessInfo = OrderProcess::where('id', $input['order_process_id'])->first()->toArray();
        //获取工单信息
        $orderInfo = Order::where('id', $orderProcessInfo['order_id'])->first()->toArray();


        //判断员工能否开工
        $orderProcessId = $orderProcessInfo['id'];
        //获取前一步骤所有工艺
        $preOrderProcessList = OrderType::getAllPrevOrderProcess($orderInfo['order_type'], $orderProcessInfo['process_type']);
        if ($preOrderProcessList) {
            $preOrderProcessList = $preOrderProcessList->toArray();
        } else {
            $preOrderProcessList = [];
        }

        //获取订单类型是否允许同时开工
        $orderTypeProcessId = OrderProcess::where('id', $orderProcessId)->first()->ordertype_process_id;
        $isMeanwhile = OrderType::isMeanwhileNextStep($orderTypeProcessId);

        $allowStart = 1;
        $message = '';
        if ($isMeanwhile) {
            //如果前面的工序已经开工则允许开工
            //前面的步骤待开工的数量（状态 1：待接单 2：待分派）
            $noStartProcessNum = OrderProcess::all()->whereIn('process_type', $preOrderProcessList)->whereIn('status', array(1, 2, 101))->where('order_id', $orderProcessInfo['order_id'])->count();
            if ($noStartProcessNum != 0) {
                $allowStart = 0;
                $message = '请等待上道工序开工';
            }
        } else {
            //判断对应步骤的工艺是否都已经完成
            $noCompleteProcessNum = OrderProcess::all()->whereIn('process_type', $preOrderProcessList)->where('status', '!=', 4)->where('order_id', $orderProcessInfo['order_id'])->count();
            if ($noCompleteProcessNum != 0) {
                $allowStart = 0;
                $message = '请等待上道工序完工';
            }
        }

        //取消领料限制
        ////主管未领料，员工开工时需要提示本工序未领取材料无法开工
        //有设置材料材料，但未领取不允许开工
//        $orderMaterialCount = \App\Eloquent\Ygt\OrderMaterial::where(['order_process_id' => $orderProcessInfo['id']])->count();
//        $orderMaterialCourseCount = \App\Eloquent\Ygt\OrderMaterialCourse::where(['order_process_id' => $orderProcessInfo['id']])->count();

//        if ($orderMaterialCount && ($orderMaterialCount > $orderMaterialCourseCount)) {
//            $allowStart = 0;
//            $message = '请等待管理员领取材料';
//        }


//        //有需要领取的材料，且材料未领取不允许开工
//        $where = [
//            ['order_process_id', '=', $orderProcessInfo['id']],
//            ['receive_number', '>', 0],
//        ];
//
//        $orderMaterialCourseReceiveCount = \App\Eloquent\Ygt\OrderMaterialCourse::where($where)->count();
//
//
//        if ($orderMaterialCourseCount && ($orderMaterialCourseCount != $orderMaterialCourseReceiveCount)) {
//            $allowStart = 0;
//            $message = '请等待管理员领取完材料';
//        }

        return [
            'code' => 0,
            'allow_start' => $allowStart,
            'message' => $message,
        ];
    }

    //主工单工单详情-新接口
    public function getOrderProductionCaseDiagram()
    {
        $orderId = request('order_id');
        if (!$orderId) {
            return [
                'code' => 1,
                'message' => '参数错误'
            ];
        }

        //获取主工单信息
        $orderInfo = Order::where(['id' => $orderId])->first();
        $imageList = [];
        if ($orderInfo['production_case_diagram']) {
            $imageIdList = explode(',', $orderInfo['production_case_diagram']);
            foreach ($imageIdList as $imageId) {
                $imageUrl = ImgUpload::getImgUrlById($imageId, true, false);
                $imageList[] = $imageUrl;
            }
        }
        return [
            'imageList' => $imageList
        ];
    }


    //员工分批提交完成数量
    public function submitOrderProcessCourseGradation()
    {
        //获取登陆用户信息
        $userId = \App\Engine\Func::getHeaderValueByName('userid');
        $userInfo = \App\Eloquent\Ygt\DepartmentUser::getCurrentInfo($userId)->toArray();

        $orderProcessCourseId = request('order_process_course_id');
        $submitNum = request('submit_num');//完成数量
        $submitWasteNum = request('submit_waste_num');

        if (!$submitNum) {
            $submitNum = 0;
        }
        if (!$submitWasteNum) {
            $submitWasteNum = 0;
        }

        if ($submitNum && $submitWasteNum) {
            return [
                'code' => 1,
                'message' => '请填写数量',
            ];
        }

        $orderProcessCourseObj = OrderProcessCourse::where(['id' => $orderProcessCourseId])->first();

        //插入员工工单分批表
        $orderProcessCourseGradationObj = OrderProcessCourseGradation::firstOrNew(['id' => '']);
        $insertRow = [];
        $insertRow['order_process_course_id'] = $orderProcessCourseId;
        $insertRow['submit_num'] = $submitNum;
        $insertRow['submit_waste_num'] = $submitWasteNum;
        $insertRow['submit_time'] = time();
        $insertRow['company_id'] = $orderProcessCourseObj->company_id;
        $insertRow['uid'] = $orderProcessCourseObj->uid;
        $orderProcessCourseGradationObj->fill($insertRow);
        $orderProcessCourseGradationObj->save();

        //修改员工工单的
        $orderProcessCourseObj->finish_number = $orderProcessCourseObj->finish_number + $submitNum;
        $orderProcessCourseObj->waste_number = $orderProcessCourseObj->waste_number + $submitWasteNum;
        $orderProcessCourseObj->save();

        //员工完工时，统计工艺完成数量并存入表中
        $orderProcessInfo = \App\Eloquent\Ygt\OrderProcess::where('id', $orderProcessCourseObj['order_process_id'])->first()->toArray();
        $orderPorcessCompleteNum = \App\Engine\OrderEngine::getOrderPorcessCompleteNum($orderProcessInfo);
        $orderProcessObj = \App\Eloquent\Ygt\OrderProcess::where('id', $orderProcessInfo['id'])->first();
        $orderProcessObj->completed_number = $orderPorcessCompleteNum;
        $orderProcessObj->save();

        //获取相关工单信息
        $orderRow = \App\Eloquent\Ygt\Order::where('id', $orderProcessInfo['order_id'])->first();


        //[如果有下一步工艺才需要半成品入库]修改为不用成品入库就有生成半成品
        $orderProcessCourseRow = $orderProcessCourseObj;
        $personnelId = $orderProcessCourseRow['uid'];
        $personnelRow = DepartmentUser::getCurrentInfo($personnelId)->toArray();
        $personnelPrivilegeId = $personnelRow['privilege_id'];
        $tmpAbleFinishedProduct = OrderEngine::getPrivilegeFinishedProduct($personnelPrivilegeId, $orderProcessInfo['ordertype_process_id']);
        $ableFinishedProduct = 0;
        if ($tmpAbleFinishedProduct) { //格式统一 1--可以 0--禁止
            $ableFinishedProduct = 1;
        }


        if(!$ableFinishedProduct){
            if($submitNum){
                //版型号（取一种）
                $plateId = 0;
                $plateNameModel = '';
                $materialName = '';
                $plateBranchId = "";
                $plateBranchColourplateId = "";
                $plateName = '';
                $plateModelName = '';
                foreach ($orderProcessInfo as $tmpKey => $tmpValue){
                    $tmpFieldType = \App\Eloquent\Ygt\ProcessFieldCompany::getFieldTypeByFieldName($tmpKey, $orderRow['company_id']);
                    if($tmpFieldType == 17){
                        if($tmpValue){
                            $tmpCreateOrderPlateRow = \App\Eloquent\Ygt\CreateOrderPlate::where(['id'=>$tmpValue])->first();
                            $plateInfo = json_decode(htmlspecialchars_decode($tmpCreateOrderPlateRow['content']), true);
                            if(!empty($plateInfo)){
                                $plateNameModel = $plateInfo['plate_name'];
                                $plateId = $plateInfo['plate_id'];

                                $tmpRe = \App\Engine\OrderEngine::getOrderPlateInfoDealId($plateInfo);
                                $plateBranchId = $tmpRe['plateBranchId'];
                                $plateBranchColourplateId = $tmpRe['plateBranchColourplateId'];
                                $plateName = $tmpRe['plateName'];
                                $plateModelName = $tmpRe['plateModelName'];

                            }

                        }
                    }elseif($tmpFieldType == 4){
                        if(!$materialName){
                            //主要材料（取一种）
                            $materialId = $tmpValue;
                            if ($materialId) {
                                $materialIdArr = explode(',',$materialId);
                                if(count($materialIdArr)){
                                    $materialId = $materialIdArr[0];
                                }

                                //获取材料信息（名称）
                                $materialObj = ProductEngine::getProductInfo($materialId);
                                $materialName = $materialId;
                                if ($materialObj) {
                                    $materialName = $materialObj->product_name;
                                }
                            }
                        }
                    }
                }
                
                //判断有没有对应的半成品生成，没有的话生成新的半成品
                if(!$plateId){
                    $plateId = 0;
                }

                //工序单位
                $curProcessMeasurementUnit = \App\Eloquent\Ygt\Process::getOneValueById($orderProcessInfo['process_type'], 'measurement_unit');
                if(!$curProcessMeasurementUnit){
                    $curProcessMeasurementUnit = '';
                }

                $tmpProcessProductRow = \App\Eloquent\Ygt\ProcessProduct::where(['ordertype_process_id'=>$orderProcessInfo['ordertype_process_id'],'order_type_id'=>$orderRow['order_type'],
                    'process_id'=>$orderProcessInfo['process_type'],'plate_id'=>$plateId,'plate_branch_id'=> $plateBranchId,'plate_branch_colourplate_id'=> $plateBranchColourplateId])->first();

                if(!$tmpProcessProductRow){
                    $tmpProcessProductRow = \App\Eloquent\Ygt\ProcessProduct::firstOrNew(['id'=>'']);
                    
                    //品名
                    $productName = \App\Engine\OrderEngine::getOrderFiledValueTrue($orderRow['product_name'], 20);

                    //片料规格
                    $chipSpecificationLength = \App\Engine\OrderEngine::getOrderFiledValueTrue($orderRow['chip_specification_length'], 15);
                    //工艺名称
                    $orderTypeTitle = \App\Engine\OrderType::getOneValueById($orderRow['order_type'], 'title');//工艺名称

                    $processTitle = Process::getOneValueById($orderProcessInfo['process_type'], 'title');

                    $tmpInsertRow = [
                        'title' => $processTitle.'半成品',
                        'ordertype_process_id' => $orderProcessInfo['ordertype_process_id'],
                        'order_type_id'=>$orderRow['order_type'],
                        'process_id'=> $orderProcessInfo['process_type'],
                        'plate_id'=> $plateId,
                        'plate_branch_id'=> $plateBranchId,
                        'plate_branch_colourplate_id'=> $plateBranchColourplateId,
                        'company_id'=> $orderRow['company_id'],
                        'buyer_name'=> $productName,
                        'plate_name'=> $plateName,
                        'plate_model'=> $plateModelName,
                        'chip_specification'=> $chipSpecificationLength,
                        'order_type_title'=> $orderTypeTitle,
                        'unit'=> $curProcessMeasurementUnit,
                        'main_material'=> $materialName,
                    ];

                    $tmpProcessProductRow->fill($tmpInsertRow);
                    $tmpProcessProductRow->save();
                }


            $tmpProcessProductRow->number = $tmpProcessProductRow['number'] + $submitNum;
            $tmpProcessProductRow->in_number = $tmpProcessProductRow['in_number'] + $submitNum;
            $tmpProcessProductRow->save();
            
            
            //增加半成品领取流水
            $tmpObj = \App\Eloquent\Ygt\ProcessProductWater::firstOrNew(['id'=>'']);
            $sn = \App\Engine\Sn::createProcessProductWaterSn();
            $tmpInsertRow = [
                'process_product_id' => $tmpProcessProductRow->id,
                'sn' => $sn,
                'number' => $submitNum,
                'unit' => $curProcessMeasurementUnit,
                'residual_number' => $tmpProcessProductRow->number,
                'company_id' => $orderRow['company_id'],
                'uid' => $personnelId,
                'privilege_id' => $personnelPrivilegeId,
                'type' => 1,//入库
            ];
            $tmpObj->fill($tmpInsertRow);
            $tmpObj->save();
            $tmpWaterId = $tmpObj->id;


            //存入待打印表
            $tmpObj = \App\Eloquent\Ygt\OrderProcessProduct::firstOrNew(['id'=>'']);
            $tmpInsertRow = [
                'order_id' => $orderProcessInfo['order_id'],
                'order_process_id' => $orderProcessInfo['id'],
                'process_type' => $orderProcessInfo['process_type'],
                'order_process_course_id' => $orderProcessCourseId,
                'order_process_course_gradation_id' => $orderProcessCourseId,
                'process_product_id' => $tmpProcessProductRow->id,
                'process_product_water_id' => $tmpWaterId,
                'number' => $submitNum,
                'status' => 1,
                'company_id' => $orderProcessInfo['company_id'],
                'uid' => $userId,
            ];
            $tmpObj->fill($tmpInsertRow);
            $tmpObj->save();


            }
        }

        //给下道工序的主管和员工发送消息
        //给下一工序的工序管理员和员工（如果已派发）发送消息
        //获取上一个部门&上一个部门
        $orderTypeObj = new OrderType();
        $nextOrderTypeProcessRow = $orderTypeObj->getNextStep($orderProcessInfo['ordertype_process_id']);//获取下一个工序
        $processOrderTypeObj = ProcessOrdertype::where(['id' => $orderProcessInfo['ordertype_process_id']])->first();
        $stepNumber = false;
        if ($processOrderTypeObj) {
            $stepNumber = $processOrderTypeObj->step_number;
        }

        $orderId = $orderProcessInfo['order_id'];
        $orderInfo = \App\Eloquent\Ygt\Order::where(['id'=>$orderId])->first();
        $foreignKey = $orderInfo['customer_order_id'];
        $tmpOrderTitle = \App\Engine\Common::changeSnCode($orderInfo['order_title']);

        $nextProcessList = OrderType::getAllNextOrderTypeProcess($orderInfo['order_type'], $orderProcessInfo['process_type'], $stepNumber);


        //获取工艺单位
        $curProcessRow = \App\Eloquent\Ygt\Process::getInfo(['id' => $orderProcessInfo['process_type']])->toArray();
        if($curProcessRow['measurement_unit']){
            $curProcessMeasurementUnit = $curProcessRow['measurement_unit'];
        }else{
            $curProcessMeasurementUnit = '';
        }
        foreach ($nextProcessList as $nextOrderTypeProcessId) {
            //给工序管理员发送消息
            $tmpNextOrderProcessRow = OrderProcess::where(['order_id' => $orderId, 'ordertype_process_id' => $nextOrderTypeProcessId])->first()->toArray();
            $tmpNextOrderProcessId = $tmpNextOrderProcessRow['id'];
            $tmpNextOrderProcessUid = $tmpNextOrderProcessRow['uid'];

            //内容：工单号、完成数量
            $userInfo = \App\Eloquent\Ygt\DepartmentUser::getCurrentInfo($userId)->toArray();
            $messageContent = "工单号：{$tmpOrderTitle}rnrn";
            $messageContent .= "完成数量：{$submitNum}{$curProcessMeasurementUnit}";

            $data = [
                'company_id' => $orderProcessInfo['company_id'],
                'privilege_id' => '',
                'form_user_id' => $userId,
                'to_user_id' => $tmpNextOrderProcessUid,
                'foreign_key' => $foreignKey,
                'type' => 35,//纯展示
                'type_id' => $orderProcessInfo['id'],
                'title' => $tmpOrderTitle,
                'content' => $messageContent,
                'theme' => "工序半成品已有数量产生",
            ];
            UserMessage::sendCustomerOrderMessage($data);


            //给已经分派了员工工单的员工发送消息
            $tmpNextOrderProcessCourseList = OrderProcessCourse::where(['order_process_id' => $tmpNextOrderProcessId])->get();
            foreach ($tmpNextOrderProcessCourseList as $tmpNextOrderProcessCourseRow) {
                $data = [
                    'company_id' => $orderProcessInfo['company_id'],
                    'privilege_id' => '',
                    'form_user_id' => $userId,
                    'to_user_id' => $tmpNextOrderProcessCourseRow->uid,
                    'foreign_key' => $foreignKey,
                    'type' => 35,//纯展示
                    'type_id' => $orderProcessInfo['id'],
                    'title' => $tmpOrderTitle,
                    'content' => $messageContent,
                    'theme' => "工序半成品已有数量产生",
                ];
                UserMessage::sendCustomerOrderMessage($data);
            }
        }

        return [
            'code' => 0,
            'message' => '提交成功',
        ];
    }

    //工序管理员修改员工提交的完工（废品）数量
    public function updateOrderProcessCourseGradation()
    {
        $orderProcessCourseGradationId = request('order_process_course_gradation_id');
        $submitNum = request('submit_num');//完成数量
        $submitWasteNum = request('submit_waste_num');

        if (!$submitNum) {
            $submitNum = 0;
        }
        if (!$submitWasteNum) {
            $submitWasteNum = 0;
        }

        if ($submitNum && $submitWasteNum) {
            return [
                'code' => 1,
                'message' => '请填写数量',
            ];
        }

        $submitDifferenceNum = $submitWasteDifferenceNum = 0;//差值
        //插入员工工单分批表
        $orderProcessCourseGradationObj = OrderProcessCourseGradation::where(['id' => $orderProcessCourseGradationId])->first();
        if ($submitNum) {
            $submitDifferenceNum = $submitNum - $orderProcessCourseGradationObj->submit_num;
            $orderProcessCourseGradationObj->submit_num = $submitNum;
        }
        if ($submitWasteNum) {
            $submitWasteDifferenceNum = $submitWasteNum - $orderProcessCourseGradationObj->submit_waste_num;
            $orderProcessCourseGradationObj->submit_waste_num = $submitWasteNum;
        }
        $orderProcessCourseGradationObj->save();

        $orderProcessCourseObj = OrderProcessCourse::where(['id' => $orderProcessCourseGradationObj['order_process_course_id']])->first();

        //修改员工工单的
        $orderProcessCourseObj->finish_number = $orderProcessCourseObj->finish_number + $submitDifferenceNum;
        $orderProcessCourseObj->waste_number = $orderProcessCourseObj->waste_number + $submitWasteDifferenceNum;
        $orderProcessCourseObj->save();

        return [
            'code' => 0,
            'message' => '提交成功',
        ];
    }


    //获取原始客户订单列表
    public function getOriginalCustomerOrderList()
    {

        $userId = Func::getHeaderValueByName('userid');
        $userInfo = DepartmentUser::getCurrentInfo($userId)->toArray();
        $companyId = isset($userInfo['company_id']) ? $userInfo['company_id'] : '';

        $where = ['company_id' => $companyId];
        $originalCustomerOrderList = FlowCustomerOrder::where($where)->orderBy('id', 'desc')->get()->toArray();


        $tmpArr = [];
        foreach ($originalCustomerOrderList as $originalCustomerOrderRow) {
            $customerId = $originalCustomerOrderRow['customer_id'];//目前没有账户id对应客户id的功能
            $customerName = '';
            if ($customerId) {
                $customerName = CustomerEngine::getNameById($customerId);
            }

            $workplaceName = '';
            if ($originalCustomerOrderRow['workplace']) {
                $workplaceName = Buyers::getNameById($originalCustomerOrderRow['workplace']);
            }

            $originalCustomerOrderRow['customer_name'] = $customerName;
            $originalCustomerOrderRow['workplace_name'] = $workplaceName;

            $tmpArr[] = $originalCustomerOrderRow;
        }

        $originalCustomerOrderList = $tmpArr;

        return $originalCustomerOrderList;
    }

    //获取原始客户订单列表
    public function getOriginalCustomerOrderDetail()
    {

        $userId = Func::getHeaderValueByName('userid');
        $userInfo = DepartmentUser::getCurrentInfo($userId)->toArray();
        $companyId = isset($userInfo['company_id']) ? $userInfo['company_id'] : '';

        $customerOrderId = request('customer_order_id');

        $where = ['id' => $customerOrderId];
        $originalCustomerOrderRow = FlowCustomerOrder::where($where)->first()->toArray();

        $customerId = 15;//目前没有账户id对应客户id的功能
        $customerName = CustomerEngine::getNameById($customerId);

        $originalCustomerOrderRow['customer_id'] = $customerId;
        $originalCustomerOrderRow['customer_name'] = $customerName;
        $originalCustomerOrderRow['workplace_name'] = Buyers::getNameById($originalCustomerOrderRow['workplace']);

        return $originalCustomerOrderRow;
    }

    //获取工单-版关联详情
    public function getOrderPlateDetail()
    {
        $orderPlateId = request('order_plate_id');
        $where = ['id' => $orderPlateId];
        $orderPlateRow = OrderPlate::where($where)->first()->toArray(0);

        $orderId = $orderPlateRow['order_id'];
        $orderProcessId = $orderPlateRow['order_process_id'];

        $showDate = date('Y-m-d', $orderPlateRow['created_at']);

        //技师
        $uid = OrderProcess::where(['id' => $orderProcessId])->first()->uid;
        if ($uid) {
            $userName = DepartmentUser::getCurrentInfo($uid)->truename;
        } else {
            $userName = '未分派';
        }

        //数量
        $orderInfo = Order::withTrashed()->where(['id' => $orderId])->first()->toArray();

//        $productNum = '';
//        if ($orderInfo['product_num']) {
//            $tmpProductNumArr = explode(',', $orderInfo['product_num']);
//            if (isset($tmpProductNumArr[0])) {
//                $productNum = $tmpProductNumArr[0];
//            }
//        }
        ////版印刷数量调整 改为工序完成数量  20180710 zhuyujun
        $productNum = $orderPlateRow['number'];


        $content = unserialize($orderPlateRow['content']);

        //获取对应工单的材料信息
        //统计工序总共使用材料情况
        $orderProcessInfo = OrderProcess::where(['id' => $orderProcessId])->first()->toArray();
        $orderProcessCourseList = OrderProcessCourse::where(['order_process_id' => $orderProcessInfo['id']])->get()->toArray();

        $orderPorcessCourseIds = [];
        $finishNum = 0;//已完成数量
        foreach ($orderProcessCourseList as $orderProcessCourseRow) {
            $orderPorcessCourseIds[] = $orderProcessCourseRow['id'];
            $finishNum += $orderProcessCourseRow['finish_number'];
        }

        $orderMaterialArr = OrderMaterialCourse::where(['process_type' => $orderProcessInfo['process_type']])->whereIn('order_process_course_id', $orderPorcessCourseIds)->get()->toArray();

        $orderMaterialListTmp = [];
        foreach ($orderMaterialArr as $orderMaterialRow) {
            if (isset($orderMaterialListTmp[$orderMaterialRow['material_id']])) {
                $orderMaterialListTmp[$orderMaterialRow['material_id']]['receive_number'] += $orderMaterialRow['receive_number'];
                $orderMaterialListTmp[$orderMaterialRow['material_id']]['residual_number'] += $orderMaterialRow['residual_number'];
                $orderMaterialListTmp[$orderMaterialRow['material_id']]['scrap_number'] += $orderMaterialRow['scrap_number'];
            } else {
                $orderMaterialListTmp[$orderMaterialRow['material_id']] = $orderMaterialRow;
            }
        }

        $orderMaterialList = [];
        foreach ($orderMaterialListTmp as $orderMaterialRow) {
            //考虑集合材料的问题
            if(strstr($orderMaterialRow['material_id'],'A')){
                $tmpAssemblageMaterialId = str_replace('A','',$orderMaterialRow['material_id']);
                $materialRow = \App\Eloquent\Ygt\AssemblageMaterial::withTrashed()->where(['id'=>$tmpAssemblageMaterialId])->first();
            }else{
                $materialRow = ProductEngine::getProductInfo($orderMaterialRow['material_id']);$materialRow = ProductEngine::getProductInfo($orderMaterialRow['material_id']);
            }

            //追加材料图片地址
            $materialRow['img_url'] = '';
            if ($materialRow['img_id']) {
                $materialRow['img_url'] = ImgUpload::getImgUrlById($materialRow['img_id']);
            }

            //增加 供应商 归属人 属性字段
            $materialRow['customer_name'] = '';
            if($materialRow['customer_id']){
                $materialRow['customer_name'] = Customer::getOneValueById($materialRow['customer_id'],'customer_name');
            }

            $materialRow['supplier_name'] = '';
            if($materialRow['seller_company_id']){
                $materialRow['supplier_name'] = SellerCompany::getOneValueById($materialRow['seller_company_id'],'title');
            }

            $materialRow['custom_fields_text']= '';
            if($materialRow['assemblage_material_id']){
                $materialRow['attr_list'] = \App\Engine\Material::getMaterialField($materialRow['assemblage_material_id']);
                $materialRow['custom_fields_text'] = $materialRow['attr_list']['custom_fields_text'];
                unset($materialRow['attr_list']);
            }

            //追加材料自定义属性
            $ProductFieldsModel = new \App\Eloquent\Ygt\ProductFields();
            $where = ['assemblage_material_id' => $materialRow['assemblage_material_id']];
            $productFields = \App\Eloquent\Ygt\ProductFields::where($where)->get();

            $productFields = $productFields->map(function ($item) {
                $data['field_name'] = $item->field_name;
                $data['is_compute'] = $item->is_compute;
                $comumnName = \App\Engine\Product::getFieldColumn($item->field_type);
                $data['field_value'] = $item->$comumnName;
                $data['unit'] = $item->unit;
                return $data;
            });

            //过滤计量属性
            $productFields = $productFields->toArray();
            foreach ($productFields as $key => $row){
                if($row['is_compute']){
                    unset($productFields[$key]);
                }
            }
            $productFields = array_values($productFields);

            $materialRow['custom_fields'] = $productFields;


            $orderMaterialRow['info'] = $materialRow;
            $orderMaterialList[] = $orderMaterialRow;
        }

        $categoryIdMaterialList = [];
        foreach ($orderMaterialList as $materialRow) {
            if (isset($categoryIdMaterialList[$materialRow['info']['category_id']])) {
                $categoryIdMaterialList[$materialRow['info']['category_id']]['list'][] = $materialRow;
            } else {
                //获取分类名称
                $categoryName = \App\Eloquent\Ygt\Category::withTrashed()->where(['id' => $materialRow['info']['category_id']])->first()->cat_name;
                $categoryIdMaterialList[$materialRow['info']['category_id']]['categoryName'] = $categoryName;
                $categoryIdMaterialList[$materialRow['info']['category_id']]['categoryId'] = $materialRow['info']['category_id'];
                $categoryIdMaterialList[$materialRow['info']['category_id']]['list'][] = $materialRow;
            }
        }


        $machine = '';

        $detailList = [];
        foreach ($categoryIdMaterialList as $categoryId => $categoryIdMaterialRow) {
            $categoryName = $categoryIdMaterialRow['categoryName'];
            $categoryId = $categoryIdMaterialRow['categoryId'];
            $detailRow = [
                'title' => $categoryName,
                'list' => [],
            ];
            foreach ($categoryIdMaterialRow['list'] as $materialRow) {
                $desc = '';
                if ($materialRow['receive_number']) {
                    $desc .= "用量：" . ($materialRow['receive_number'] - $materialRow['residual_number'] - $materialRow['scrap_number']) . "({$materialRow['info']['unit']})";
                }

                $detailRow['list'][] = [
                    'name' => $materialRow['info']['product_name'],
                    'imgUrl' => $materialRow['info']['img_url'],
                    'customer_name' => $materialRow['info']['customer_name'],
                    'supplier_name' => $materialRow['info']['supplier_name'],
                    'custom_fields_text' => $materialRow['info']['custom_fields_text'],
                    'desc' => $desc,
                ];

            }
            $detailList[] = $detailRow;
        }


//        $orderPlateField = OrderEngine::getOrderPlateField();
//        $detailList = [];
//        foreach ($orderPlateField as $item => $filedRow) {
//            if ($item == 'machine') {
//                $machine = $content[$item];
//                continue;
//            }
//
//            $tmpListStr = $content[$item];
//            if ($tmpListStr) {
//                $tmpValueList = explode(',', $tmpListStr);
//                foreach ($tmpValueList as $tmpRow) {
//                    //判断是否是数字
//                    if (is_numeric($tmpRow)) {
//                        $collection = ProductEngine::getProductInfo($tmpRow);
//                        if ($collection) {//过滤异常情况
//                            $info = $collection->toArray();
//                            $tmpRow = $info['product_name'];
//                        }
//                    }
//
//                    $tmpList[] = [
//                        'name' => $tmpRow,
//                        'imgUrl' => '',
//                        'desc' => '',
//                    ];
//                }
//            } else {
//                $tmpList = [];
//            }
//
//            $detailList[] = [
//                'title' => $filedRow['title'],
//                'list' => $tmpList
//            ];
//        }

        $re = [
            'userName' => $userName,//技师
            'machine' => $machine,//机台
            'showDate' => $showDate,//展示日期
            'productNum' => $productNum . '条',//数量
            'detailList' => $detailList,//用料详情
        ];
        return $re;
    }

    //通过客户id获取工厂列表
    public function getCompanyList()
    {
        $userId = Func::getHeaderValueByName('userid');
        $userInfo = DepartmentUser::getCurrentInfo($userId)->toArray();


        $companyList = [];
        $customerRow = Customer::where(['user_id' => $userId])->first();
        if ($customerRow) {
            $companyId = $customerRow->company_id;
            $companyName = Company::getOneValueById($companyId, 'title');
            $tmpArr = [
                'company_id' => $companyId,
                'company_name' => $companyName,
            ];
            $companyList[] = $tmpArr;
        }

        if (empty($companyList)) {
            //获取用户对应的厂
            $companyId = $userInfo['company_id'];
            $companyName = Company::getOneValueById($companyId, 'title');
            $tmpArr = [
                'company_id' => $companyId,
                'company_name' => $companyName,
            ];
            $companyList[] = $tmpArr;
        }

        return $companyList;
    }


    /**
     * Description:提交工单类型
     * User: zhuyujund
     * @param Request $request
     * @return array
     */
    public function customerOrderTypeSubmit(Request $request)
    {
        //获取传入数据
        $input = $request->all();
        //获取工单类型id
        //校验参数
        $rules = [
            'order_type' => 'required',
        ];
        $message = [
            'order_type.required' => '未选择订单类型'
        ];
        $this->validateRequestParameters($input, $rules, true, $message);

        //是否归档
//        $isFile = request('is_file');


        //创建预生成订单&返回预生成订单id
        $customerOrderId = request('customer_order_id');
        $customerOrderPreRow = CustomerOrderPre::firstOrNew(['id' => $customerOrderId]);

        //订单号调整为正式生成订单时创建
//        $orderTitle = 'D' . time() . rand(0, 9) . rand(0, 9) . rand(0, 9) . rand(0, 9) . rand(0, 9) . rand(0, 9);
        $orderTitle = '';

        //用户id&企业id
        $userId = Func::getHeaderValueByName('userid');
        $userInfo = DepartmentUser::getCurrentInfo($userId)->toArray();

        $companyId = OrderType::getOneValueById($input['order_type'], 'company_id');


        //获取userid对应的客户id
        $customerId = request('customer_id');
        if (!$customerId) {
            $customerId = OrderEngine::getCustomerIdByUid($userId);
        }

        $insertRow = [
            'order_type' => $input['order_type'],
            'order_title' => $orderTitle,
            'uid' => $userId,
            'company_id' => $companyId,
            'is_trash' => 1,//默认设置为该记录为可删除
//            'is_file' => $isFile,//是否归档
            'customer_name' => $customerId,//客户id
        ];


        $customerOrderPreRow->fill($insertRow);
        $customerOrderPreRow->save();
        $orderId = $customerOrderPreRow->id;

        return ['order_id' => $orderId];
    }

    /**
     * Description:订单创建-基础信息-选项参数获取
     * User: zhuyujun
     * @param Request $request
     * @return array
     */
    public function customerOrderPreBaseInfo(Request $request)
    {
        //获取传入数据
        $input = $request->all();
        $input['copy_order_id'] = isset($input['copy_order_id']) ? $input['copy_order_id'] : '';//被复制的订单id 测试数据
        $pre_order_id = isset($input['pre_order_id']) ? $input['pre_order_id'] : '';//草稿箱订单id 测试数据

        $curOrderRow = CustomerOrderPre::where(['id' => $input['order_id']])->first()->toArray();
        $distributionOrderId = $input['order_id'];
        if ($pre_order_id !== '') {
            //草稿箱
            $curOrderRow = CustomerOrderPre::where(['id' => $pre_order_id])->first()->toArray();
            $orderId = $pre_order_id;
            $distributionOrderId = $orderId;
        } else if ($input['copy_order_id']) {
            //再来一单
            //校验参数
            $rules = [
                'order_id' => 'required',
            ];
            $message = [
                'order_id.required' => '未获取到到订单id'
            ];
            $this->validateRequestParameters($input, $rules, true, $message);
            $curOrderRow = CustomerOrder::where(['id' => $input['copy_order_id']])->first()->toArray();
            //获取订单类型id
            $orderId = $input['order_id'];
            $distributionOrderId = $input['copy_order_id'];
        } else {
            //校验参数
            $rules = [
                'order_id' => 'required',
            ];
            $message = [
                'order_id.required' => '未获取到到订单id'
            ];
            $this->validateRequestParameters($input, $rules, true, $message);
            $orderId = $input['order_id'];
        }

        //订单基础信息字段，目前格式固定
//        $orderBaseFieldList = $this->orderBaseFieldList();
        $userId = Func::getHeaderValueByName('userid');
        $userInfo = DepartmentUser::getCurrentInfo($userId)->toArray();


        $companyId = $curOrderRow['company_id'];
        $orderBaseFieldList = OrderFieldCompany::getActiveFieldList($companyId);

        //添加默认值
        if (!empty($curOrderRow)) {
            foreach ($orderBaseFieldList as $key => $row) {
                if (isset($curOrderRow[$row['field_name']]) && $curOrderRow[$row['field_name']]) {
                    if ($row['field_type'] == 5) {//填写+单位选择 处理
                        $oldRow = $curOrderRow[$row['field_name']];
                        $oldRowArr = explode(',', $oldRow);
                        if (count($oldRowArr) > 1) {
                            $defaultValue = $oldRowArr[0];
                            $oldUnitTitle = $oldRowArr[1];
                            $oldUnitId = $this->getUnitIdByTitle($oldUnitTitle, $row['field_unit']);
                            if (!$oldUnitId) {
                                if (count($row['field_unit'])) {
                                    $oldUnitId = $row['field_unit'][0]['id'];
                                    $oldUnitTitle = $row['field_unit'][0]['title'];
                                } else {
                                    $oldUnitId = 0;
                                    $oldUnitTitle = '';
                                }
                            }

                            $orderBaseFieldList[$key]['default_value'] = $defaultValue;
                            $orderBaseFieldList[$key]['default_unit_id'] = $oldUnitId;
                            $orderBaseFieldList[$key]['default_unit_title'] = $oldUnitTitle;
                        }
                    } elseif ($row['field_type'] == 8) {//配送地址 处理
                        $customerAddressId = $curOrderRow[$row['field_name']];

//                        $customerAddressRow = CustomerAddress::where(['id' => $customerAddressId])->first();
                        $addressWhere = ['id' => $customerAddressId];
                        $customerAddress = \App\Eloquent\Ygt\BuyersAddress::withTrashed()->where($addressWhere)->first();
                        $customerAddressRow = [];
                        if ($customerAddress) {
                            $customerAddressRow = $customerAddress->toArray();
                        }
                        $showTitle = $customerAddressRow['province_name'] . $customerAddressRow['city_name'] . $customerAddressRow['area_name'];

                        $orderBaseFieldList[$key]['default_select_id'] = $customerAddressId;
                        $orderBaseFieldList[$key]['default_value'] = $showTitle;

                    } elseif ($row['field_type'] == 9) {//图片处理
                        $oldImgRow = $curOrderRow[$row['field_name']];
                        $imgIdList = explode(',', $oldImgRow);

                        $imgUrlListStr = '';
                        foreach ($imgIdList as $imgId) {
                            if (!trim($imgId)) {//过滤空格 图片id应该不会有0
                                continue;
                            }
                            $imgUrl = ImgUpload::getImgUrlById($imgId);
                            $imgUrlListStr .= $imgUrl . ',';
                        }

                        $imgUrlListStr = trim($imgUrlListStr, ',');
                        $orderBaseFieldList[$key]['default_img_id'] = $oldImgRow;
                        $orderBaseFieldList[$key]['default_img_url'] = $imgUrlListStr;
                    } elseif ($row['field_type'] == 17) {//版 处理
//                        $selectId = $curOrderRow[$row['field_name']];
//                        $orderBaseFieldList[$key]['default_select_id'] = $selectId;
//                        $plateRow = PlateEngine::getPlateInfo($selectId);
//
//                        if ($plateRow) {
////                            $tmpObj = \App\Eloquent\Ygt\BuyersProduct::where(['id'=>$plateRow['plate_name']])->first();
////                            if($tmpObj){
////                                $showTitle = $tmpObj['name'];
////                            }else{
////                                $showTitle = $plateRow['plate_name'];
////                            }
//                            //改为显示版号 zhuyujun 20180704
//                            $showTitle = $plateRow['plate_no'];
//
//                        } else {
//                            $showTitle = $curOrderRow[$row['field_name']];
//                        }
//
//                        $orderBaseFieldList[$key]['default_value'] = $showTitle;
                        //新的版数据
                        $tmpCreateOrderPlateRow = \App\Eloquent\Ygt\CreateOrderPlate::where(['id'=>$curOrderRow[$row['field_name']]])->first();
                        $plateInfo = json_decode(htmlspecialchars_decode($tmpCreateOrderPlateRow['content']), true);;
                        if(empty($plateInfo)){
                            $plateInfo = null;
                        }

                        $orderBaseFieldList[$key]['default_value'] = '';
                        $orderBaseFieldList[$key]['default_plate_list'] = $plateInfo;

                    } elseif ($row['field_type'] == 18) {//客户 处理
                        $selectId = $curOrderRow[$row['field_name']];
                        $orderBaseFieldList[$key]['default_select_id'] = $selectId;

                        $customerTitle = CustomerEngine::getNameById($selectId);
                        if ($customerTitle) {
                            $showTitle = $customerTitle;
                        } else {
                            $showTitle = $curOrderRow[$row['field_name']];
                        }
                        $orderBaseFieldList[$key]['default_value'] = $showTitle;
                    } elseif ($row['field_type'] == 19) {//单位 处理
                        $selectId = $curOrderRow[$row['field_name']];
                        $orderBaseFieldList[$key]['default_select_id'] = $selectId;

                        $buyersTitle = Buyers::getNameById($selectId);
                        if ($buyersTitle) {
                            $showTitle = $buyersTitle;
                        } else {
                            $showTitle = $curOrderRow[$row['field_name']];
                        }
                        $orderBaseFieldList[$key]['default_value'] = $showTitle;
                    } elseif ($row['field_type'] == 20) {//品名 处理
                        $selectId = $curOrderRow[$row['field_name']];
                        $orderBaseFieldList[$key]['default_select_id'] = $selectId;

                        $buyersProduct = \App\Eloquent\Ygt\BuyersProduct::where(['id' => $selectId])->first();

                        if ($buyersProduct) {
                            $showTitle = $buyersProduct['name'];
                        } else {
                            $showTitle = $curOrderRow[$row['field_name']];
                        }
                        $orderBaseFieldList[$key]['default_value'] = $showTitle;
                    } elseif ($row['field_type'] == 21) {//开票资料 处理
                        $selectId = $curOrderRow[$row['field_name']];
                        $orderBaseFieldList[$key]['default_select_id'] = $selectId;

                        $buyersInvoice = \App\Eloquent\Ygt\BuyersInvoice::where(['id' => $selectId])->first();

                        if ($buyersInvoice) {
                            $showTitle = $buyersInvoice['account_name'];
                        } else {
                            $showTitle = $curOrderRow[$row['field_name']];
                        }
                        $orderBaseFieldList[$key]['default_value'] = $showTitle;
                    }elseif ($row['field_type'] == 22) {//半成品展示

                        $tmpCreateOrderProcessProductRow = \App\Eloquent\Ygt\CreateOrderProcessProduct::where(['id'=>$curOrderRow[$row['field_name']]])->first();
                        $processProductInfo = json_decode(htmlspecialchars_decode($tmpCreateOrderProcessProductRow['content']), true);
                        if(empty($processProductInfo)){
                            $processProductInfo = null;
                        }

                        $orderBaseFieldList[$key]['default_value'] = '';
                        $orderBaseFieldList[$key]['default_process_product_list'] = $processProductInfo;

                    }
                    else {
                        $orderBaseFieldList[$key]['default_value'] = $curOrderRow[$row['field_name']];
                    }
                }

            }
        }

        $orderPreRow = CustomerOrderPre::where('id', $orderId)->first()->toArray();
        $orderType = $orderPreRow['order_type'];

        $processNum = OrderType::getAllOrderTypeProcess($orderType)->count();

        $related_feedback_num = \App\Eloquent\Ygt\CustomerOrderFeedback
            ::leftJoin('ygt_customer_order','ygt_customer_order_feedback.customer_order_id','=','ygt_customer_order.id')
            ->where('ygt_customer_order.order_type','=',$orderType)
            ->count();

        return [
            'related_feedback_num'=>$related_feedback_num?sprintf("类似订单有反馈"):'',
            'process_title' => '基础信息',
            'order_base_field_list' => $orderBaseFieldList,
            'button_title' => '下一步',
            'create_order_title' => '创建订单（1/' . ($processNum + 1) . '）'
        ];
    }

    /**
     * Description:订单创建-基础信息-提交
     * User: zhuyujun
     * @param Request $request
     * @return array
     */
    public function customerOrderPreBaseSubmit(Request $request)
    {
        //获取传入数据
        $input = $request->all();
        $input['is_draft'] = isset($input['is_draft']) ? $input['is_draft'] : 0;//是否存入草稿箱，是的话不校验数据

        $userId = Func::getHeaderValueByName('userid');
        $userInfo = DepartmentUser::getCurrentInfo($userId)->toArray();

        $curOrderRow = CustomerOrderPre::where(['id' => $input['order_id']])->first()->toArray();
        $companyId = $curOrderRow['company_id'];

        $orderBaseFieldList = OrderFieldCompany::getActiveFieldList($companyId);
        //验证字段是必填还是选填 by zzy
        if (!$input['is_draft']) {
            $process_field_list = $orderBaseFieldList;
            $processFieldRules = [];
            $processFieldMessage = [];
            foreach ($process_field_list as $key => $val) {
                $isMust = $val['is_must'];
                if ($isMust == 1) {
                    $rulesName = 'required';
                    $fieldName = $val['field_name'];
                    $fieldTitle = $val['title'];
                    $fieldMsg = $fieldName . '.' . $rulesName;
                    $processFieldRules[$fieldName] = $rulesName;
                    $processFieldMessage[$fieldMsg] = $fieldTitle . '必填';

                    $inputValue = $input[$fieldName];
                    if (empty($inputValue)) {
                        xThrow(ERR_PARAMETER, $fieldTitle . '必填');
                    }
                }
            }
        }


        //数据入库
        //创建预生成订单&返回预生成订单id
        $orderId = $input['order_id'];
        $orderPreRow = CustomerOrderPre::firstOrNew(['id' => $orderId]);
        $orderType = $orderPreRow->order_type;

        //修改数据
        foreach ($orderBaseFieldList as $fieldRow) {
            if (isset($input[$fieldRow['field_name']])) {
                $tmpFieldName = $fieldRow['field_name'];

                if($fieldRow['field_type'] == 17){
                    $tmpObj = \App\Eloquent\Ygt\CreateOrderPlate::firstOrNew(['id'=>'']);
                    $tmpInsertRow = [
                        'type' => 1,
                        'relate_id' => $input['order_id'],
                        'field_name' => $tmpFieldName,
                        'content' => $input[$fieldRow['field_name']],
                    ];

                    $tmpObj->fill($tmpInsertRow);
                    $tmpObj->save();
                    $createOrderPlateId = $tmpObj->id;

                    $orderPreRow->$tmpFieldName = $createOrderPlateId;
                }
                else if($fieldRow['field_type'] == 4){//可以不加的，以防万一
                    $input = OrderEngine::handleInput($input,$fieldRow['field_name'],$fieldRow['field_type'],'purchase_info');
                    $orderPreRow->$tmpFieldName = $input[$fieldRow['field_name']];
                }
                else{
                    $orderPreRow->$tmpFieldName = $input[$fieldRow['field_name']];
                }
            }
        }

        //限制交货日期
        if (isset($input['finished_date']) && $input['finished_date']) {
            if (strtotime($input['finished_date']) < strtotime(date('Ymd'))) {
                return [
                    'code' => 1,
                    'message' => '交货日期不能早于今天'
                ];
            }
        }


        $orderPreRow->status = 1;//订单状态 1-待确认 2-待派单 3-待生产 4-生产中 5-已完工 6-已发货 7-已收讫
        $orderPreRow->is_trash = 0;//标记为不自动删除
        $orderPreRow->save();
        $orderPreRow->id;

        //返回该订单类型的第一个工序
        $orderTypeObj = new OrderType();
        $firstProcessRow = $orderTypeObj->getFirstStep($orderType);
        $firstProcessId = $firstProcessRow['process_id'];
        $firstOrdertypeProcessId = $firstProcessRow['id'];

        return [
            'process_id' => $firstProcessId,
            'ordertype_process_id' => $firstOrdertypeProcessId,
        ];
    }

    //当版只有一种组合时，组建默认版信息
    //当版只有一种组合时，组建默认版信息
    private function getDefaultPlateInfo($buyers_product_id,$extra_info = []){
//        $buyers_product_id =  224;
        $plate_id = 0;
        $plate_name = '';
        $category_id = 0;
        $num = 0;
        if(isset($extra_info['num'])){
            $num = $extra_info['num'];
        }
        $ret = ['is_have_info'=>1];
        //获得品名
        $buyers_product_info = BuyersProduct::where('id','=',$buyers_product_id)->first();
        if(!$buyers_product_info){
            $ret['is_have_info'] = 0;
            return $ret;
        }
        $buyers_product_info = $buyers_product_info->toArray();

        $plate_name = $buyers_product_info['name'];
        //获得版信息
        $plate_list = Plate::where('plate_name','=',$buyers_product_id)
            ->get();
        if($plate_list){
            $plate_list = $plate_list->toArray();
            if(count($plate_list)==1){
                $plate_info = $plate_list[0];
                $plate_id = $plate_info['id'];
                $category_id = $plate_info['category_id'];
            }
            else{
                $ret['is_have_info'] = 0;
                return $ret;
            }
        }
        else{
            $ret['is_have_info'] = 0;
            return $ret;
        }

        //非电雕版
        if($category_id != 1){
            //获得支板信息
            $plate_branch_list = PlateBranch::where('plate_id','=',$plate_id)
                ->where('is_choose','=',1)->get();
            if($plate_branch_list){
                $plate_branch_list = $plate_branch_list->toArray();
                if(count($plate_branch_list) == 1){
                    $plate_branch_info =$plate_branch_list[0];
                    $ret['plate_name'] = $plate_name;
                    $ret['plate_id'] = $plate_id;
                    $ret['category_id'] = $category_id;
                    $ret['branch']['other_plate'][] = [
                        'name'=>$plate_branch_info['name'],
                        'num'=>$num

                    ];
                    return $ret;
                }
                //无型号
                else if(count($plate_branch_list) == 0){
                    $ret['plate_name'] = $plate_name;
                    $ret['plate_id'] = $plate_id;
                    $ret['category_id'] = $category_id;
                    $ret['branch']['other_plate'][] = [
                        'name'=>$plate_name,
                        'num'=>$num
                    ];
                    return $ret;
                }
                else{
                    $ret['is_have_info'] = 0;
                    return $ret;
                }
            }
            else{
                $ret['is_have_info'] = 0;
                return $ret;
            }
        }
        //电雕版
        else{
            //获得支板信息 套版
            $plate_branch_list_t = PlateBranch::where('plate_id','=',$plate_id)
                ->where('is_choose','=',1)
                ->where('type','=',2)
                ->get();
            if($plate_branch_list_t){
                $plate_branch_list_t = $plate_branch_list_t->toArray();
            }
            else{
                $plate_branch_list_t = [];
            }

            //获得固定板信息
            $plate_branch_list_g = PlateBranch::where('plate_id','=',$plate_id)
                ->where('is_choose','=',1)
                ->where('type','=',1)
                ->get();
            if($plate_branch_list_g){
                $plate_branch_list_g = $plate_branch_list_g->toArray();
            }
            else{
                $plate_branch_list_g = [];
            }

            //无固定板，无套版
            if(!count($plate_branch_list_t) && !count($plate_branch_list_g)){
                $ret['is_have_info'] = 0;
                return $ret;
            }

            //有型号
            if(count($plate_branch_list_t)>0){
                $fixed_plate = [];
                foreach($plate_branch_list_g as $key=>$val){
                    $fixed_plate[] = [
                        'name'=>$val['name'],
                        'sort'=>$key
                    ];
                }

                $group = [];
                foreach($plate_branch_list_t as $key=>$val){
                    $plate_branch_colourplate_list = PlateBranchColourplate::where('plate_branch_id','=',$val['id'])->get();
                    if($plate_branch_colourplate_list){
                        $plate_branch_colourplate_list = $plate_branch_colourplate_list->toArray();
                        if(count($plate_branch_colourplate_list)==1){
                            $plate_branch_colourplate = $plate_branch_colourplate_list[0];
                            $group[] = [
                                'name'=>$plate_branch_colourplate['plate_branch_name'],
                                'model'=>$plate_branch_colourplate['name']
                            ];
                        }
                        else{
                            $ret['is_have_info'] = 0;
                            return $ret;
                        }
                    }
                    else{
                        $ret['is_have_info'] = 0;
                        return $ret;
                    }
                }

                $ret['plate_name'] = $plate_name;
                $ret['plate_id'] = $plate_id;
                $ret['category_id'] = $category_id;
                $ret['branch']['colourplate'][] = [
                        'group'=>$group,
                        'num'=>$num
                ];

                $ret['branch']['fixed_plate']=$fixed_plate;
            }
            //无型号
            else{
                $fixed_plate = [];
                foreach($plate_branch_list_g as $key=>$val){
                    $fixed_plate[] = [
                        'name'=>$val['name'],
                        'sort'=>$key
                    ];
                }

                $ret['plate_name'] = $plate_name;
                $ret['plate_id'] = $plate_id;
                $ret['category_id'] = $category_id;
                $ret['branch']['colourplate'][] = [
                    'group'=>[],
                    'num'=>$num
                ];

                $ret['branch']['fixed_plate']=$fixed_plate;
            }

        }

        return $ret;
    }



    //工序信息获取统一接口
    public function getCustomerProcessDetail(Request $request)
    {
        //获取传入数据
        $input = $request->all();
        $input['process_id'] = isset($input['process_id']) ? $input['process_id'] : '';//订单工序类型id
        $input['ordertype_process_id'] = isset($input['ordertype_process_id']) ? $input['ordertype_process_id'] : 0;//订单工序类型id
        $input['order_id'] = isset($input['order_id']) ? $input['order_id'] : '';//订单id 测试数据1
        $input['copy_order_id'] = isset($input['copy_order_id']) ? $input['copy_order_id'] : '';//被复制的订单id 测试数据
        $pre_order_id = isset($input['pre_order_id']) ? $input['pre_order_id'] : '';//草稿箱订单id 测试数据

        $curOrderProcessRow = [];
        if ($pre_order_id) {
            $curOrderProcessRow = CustomerOrderProcessPre::where(['order_id' => $pre_order_id, 'process_type' => $input['process_id']])->first();
            if ($curOrderProcessRow) {
                $curOrderProcessRow = $curOrderProcessRow->toArray();
            }
            $input['order_id'] = $pre_order_id;
        } elseif ($input['copy_order_id']) {//如果传入复制订单id
            $customerOrderProcessObj = CustomerOrderProcess::where(['order_id' => $input['copy_order_id'], 'process_type' => $input['process_id']])->first();
            if ($customerOrderProcessObj) {
                $curOrderProcessRow = $customerOrderProcessObj->toArray();
            } else {
                $curOrderProcessRow = [];
            }
        }


        //获取订单信息
        $orderInfo = CustomerOrderPre::where(['id' => $input['order_id']])->first()->toArray();
        $orderType = $orderInfo['order_type'];

        //通过工序id，获取对应的字段
        $processFieldList = Process::getFieldListByProcessId($input['process_id']);

        //获取工序信息
        $processTitle = Process::getOneValueById($input['process_id'], 'title');

        //是否为工艺上最后一个工序
        $orderTypeObj = new OrderType();
        if ($input['ordertype_process_id']) {//新旧兼容
            $nextOrderTypeProcessRow = $orderTypeObj->getNextStep($input['ordertype_process_id']);//获取下一个工序
            $nextProcessId = $nextOrderTypeProcessRow[0]['process_id'];
        } else {
            $nextProcessId = $orderTypeObj->getNextOneProcessId($orderType, $input['process_id']);//获取下一个工序
        }


        $buttonTitle = '';
        $isToCreate = 0;
        if ($nextProcessId) {
            $buttonTitle = '下一步';//按钮显示文字
        } else {
            $buttonTitle = '保存';//按钮显示文字
            $isToCreate = 1;
        }

        //获取工艺数目
        $curProcessNum = OrderType::getOrderTypeProcessNumber($orderType, $input['process_id']);
        $processNum = OrderType::getAllOrderTypeProcess($orderType)->count();

        //添加默认值
        if (!empty($curOrderProcessRow)) {
            foreach ($processFieldList as $key => $row) {
                if (isset($curOrderProcessRow[$row['field_name']]) && $curOrderProcessRow[$row['field_name']]) {
                    if ($row['field_type'] == 3) {//选择 处理
                        $selectId = $this->getSidByTitle($curOrderProcessRow[$row['field_name']], $row['data']);
                        $processFieldList[$key]['default_select_id'] = $selectId;
                        $processFieldList[$key]['default_value'] = $curOrderProcessRow[$row['field_name']];
                    } elseif ($row['field_type'] == 5) {//填写+单位选择 处理
                        $oldRow = $curOrderProcessRow[$row['field_name']];
                        $oldRowArr = explode(',', $oldRow);
                        if (count($oldRowArr) > 1) {//异常数据处理
                            $defaultValue = $oldRowArr[0];
                            $oldUnitTitle = $oldRowArr[1];
                            $oldUnitId = $this->getUnitIdByTitle($oldUnitTitle, $row['field_unit']);
                            if (!$oldUnitId) {
                                if (count($row['field_unit'])) {
                                    $oldUnitId = $row['field_unit'][0]['id'];
                                    $oldUnitTitle = $row['field_unit'][0]['title'];
                                } else {
                                    $oldUnitId = 0;
                                    $oldUnitTitle = '';
                                }
                            }

                            $processFieldList[$key]['default_value'] = $defaultValue;
                            $processFieldList[$key]['default_unit_id'] = $oldUnitId;
                            $processFieldList[$key]['default_unit_title'] = $oldUnitTitle;
                        }
                    } elseif ($row['field_type'] == 4) {//选择材料页面
                        $materialIdListStr = $curOrderProcessRow[$row['field_name']];
                        $materialIdList = explode(',', $materialIdListStr);
                        //获取优选采购的材料id
                        $recommendMaterialIdArr = OrderMaterialPurchaseMark::where('customer_order_pre_id','=',$orderInfo['id'])->where('is_purchase','=',1)->pluck('material_id')->toArray();
                        $materialList = [];
                        foreach ($materialIdList as $materialId) {
                            //考虑集合材料的问题
                            if(strstr($materialId,'A')){
                                $tmpAssemblageMaterialId = str_replace('A','',$materialId);
                                $materialRow = \App\Eloquent\Ygt\AssemblageMaterial::withTrashed()->where(['id'=>$tmpAssemblageMaterialId])->first();

                            }else{
                                $materialRow = ProductEngine::getProductInfo($materialId);
                            }

                            if ($materialRow) {//过滤异常情况
                                //增加材料图片地址 20180719 zhuyujun
                                //追加材料图片地址
                                $materialRow['img_url'] = '';

                                if ($materialRow['img_id']) {
                                    $materialRow['img_url'] = \App\Eloquent\Ygt\ImgUpload::getImgUrlById($materialRow['img_id']);
                                }

                                $materialRow->toArray();

                                //处理价格问题
                                $priceColor = '#000000';

                                if($input['copy_order_id']){
                                    //获取订单对应的工单(最近的)
                                    $tmpCustomerOrderId = $input['copy_order_id'];
                                    $tmpOrderRow = \App\Eloquent\Ygt\Order::where(['customer_order_id'=>$tmpCustomerOrderId])->orderBy('id','desc')->first();
                                    if($tmpOrderRow){
                                        //上次的价格
                                        $tmpPreMaterialPrice = 0;
                                        $tmpOrderMaterialRow = \App\Eloquent\Ygt\OrderMaterial::where(['order_id'=>$tmpOrderRow['id'],'material_id'=>$materialId])->first();
                                        if($tmpOrderMaterialRow){
                                            $tmpPreMaterialPrice = $tmpOrderMaterialRow['price'];
                                        }

                                        //现在的价格
                                        $tmpCurMaterialPrice = \App\Engine\Material::getMaterialPrice($materialId);

                                        if($tmpPreMaterialPrice && $tmpCurMaterialPrice){//如果没有值不做比较
                                            //价格降了（绿色）
                                            if($tmpPreMaterialPrice > $tmpCurMaterialPrice){
                                                $priceColor = "#7CFC00";
                                            }

                                            //价格涨了（红色）
                                            if($tmpPreMaterialPrice < $tmpCurMaterialPrice){
                                                $priceColor = "#EE3B3B";
                                            }
                                        }

                                    }

                                }

                                if(in_array($materialId,$recommendMaterialIdArr)){
                                    $materialRow['is_purchase'] = 1;
                                }
                                else{
                                    $materialRow['is_purchase'] = 0;
                                }

                                $materialList[] = [
                                    'id' => $materialId,
                                    'product_no' => $materialRow['product_no'],
                                    'product_name' => $materialRow['product_name'],
                                    'image_path' => $materialRow['img_url'],
                                    'is_purchase' => $materialRow['is_purchase'],
                                    'price_color' => $priceColor,
                                ];
                            }
                        }


                        $processFieldList[$key]['default_product_list'] = $materialList;
                    }elseif ($row['field_type'] == 17) {//版 处理
//                        $selectId = $curOrderProcessRow[$row['field_name']];
//                        $processFieldList[$key]['default_select_id'] = $selectId;
//                        $plateRow = PlateEngine::getPlateInfo($selectId);
//
//                        if ($plateRow) {
////                            $tmpObj = \App\Eloquent\Ygt\BuyersProduct::where(['id'=>$plateRow['plate_name']])->first();
////                            if($tmpObj){
////                                $showTitle = $tmpObj['name'];
////                            }else{
////                                $showTitle = $plateRow['plate_name'];
////                            }
//                            $showTitle = $plateRow['plate_no'];
//                        } else {
//                            $showTitle = $curOrderProcessRow[$row['field_name']];
//                        }
//
//                        $processFieldList[$key]['default_value'] = $showTitle;


                        //新的版数据
                        $tmpCreateOrderPlateRow = \App\Eloquent\Ygt\CreateOrderPlate::where(['id'=>$curOrderProcessRow[$row['field_name']]])->first();
                        $plateInfo = json_decode(htmlspecialchars_decode($tmpCreateOrderPlateRow['content']), true);
                        if(empty($plateInfo)){
                            $plateInfo = null;
                        }

                        $processFieldList[$key]['default_value'] = '';
                        $processFieldList[$key]['default_plate_list'] = $plateInfo;

                    } elseif ($row['field_type'] == 18) {//客户 处理
                        $selectId = $curOrderProcessRow[$row['field_name']];
                        $processFieldList[$key]['default_select_id'] = $selectId;

                        $customerTitle = CustomerEngine::getNameById($selectId);
                        if ($customerTitle) {
                            $showTitle = $customerTitle;
                        } else {
                            $showTitle = $curOrderProcessRow[$row['field_name']];
                        }
                        $processFieldList[$key]['default_value'] = $showTitle;
                    } elseif ($row['field_type'] == 19) {//单位展示
                        $baseId = $curOrderProcessRow[$row['field_name']];
                        $showTitle = Buyers::getNameById($baseId);
                        if (!$showTitle) {
                            $showTitle = $curOrderProcessRow[$row['field_name']];
                        }
                        $processFieldList[$key]['default_value'] = $showTitle;
                    } elseif ($row['field_type'] == 22) {//半成品展示


                        $tmpCreateOrderProcessProductRow = \App\Eloquent\Ygt\CreateOrderProcessProduct::where(['id'=>$curOrderProcessRow[$row['field_name']]])->first();
                        $processProductInfo = json_decode(htmlspecialchars_decode($tmpCreateOrderProcessProductRow['content']), true);
                        if(empty($processProductInfo)){
                            $processProductInfo = null;
                        }

                        $processFieldList[$key]['default_value'] = '';
                        $processFieldList[$key]['default_process_product_list'] = $processProductInfo;


                    }else {
                        $processFieldList[$key]['default_value'] = $curOrderProcessRow[$row['field_name']];
                    }
                }
            }
        }
        else{
            //当版组合只有一种的时候，返回默认信息
            $numArr = explode(',',$orderInfo['product_num']);
            $plateInfo = $this->getDefaultPlateInfo($orderInfo['product_name'],['num'=>$numArr[0]]);
            if(!$plateInfo['is_have_info']){
                $plateInfo = null;
            }
            foreach ($processFieldList as $key => $row) {
                if ($row['field_type'] == 17) {//版 处理
                    $processFieldList[$key]['default_value'] = '';
                    $processFieldList[$key]['default_plate_list'] = $plateInfo;
                }
            }


        }

        //追加再基础信息中填写的客户id
        $customerId = $customerName =  '';
        if (isset($orderInfo['customer_name']) && $orderInfo['customer_name'] && $orderInfo['customer_name'] != '(null)') {
            $customerId = $orderInfo['customer_name'];
            if($customerId){
                $tmpObj = \App\Eloquent\Ygt\Customer::where(['id'=>$customerId])->first();
                if($tmpObj){
                    $customerName = $tmpObj->customer_name;
                }
            }
        }

        //追加再基础信息中填写的品名id
        $plateNameId = '';
        if (isset($orderInfo['product_name']) && $orderInfo['product_name'] && $orderInfo['product_name'] != '(null)') {
            $plateNameId = $orderInfo['product_name'];
        }

        $return = [];
        $return['customer_id'] = $customerId;//基础信息中选的客户ID
        $return['plate_name_id'] = $plateNameId;//基础信息的品名ID
        $return['customer_name'] = $customerName;//基础信息中选的客户名称
        $return['process_title'] = $processTitle;//工序名称
        $return['process_field_list'] = $processFieldList;//工序字段
        $return['button_title'] = $buttonTitle;//按钮显示文字
        $return['is_to_create'] = $isToCreate;//最后一步工序（需要展示归档还是创建订单）
        $return['create_order_title'] = '创建订单（' . ($curProcessNum + 1) . '/' . ($processNum + 1) . '）';//按钮显示文字

        return $return;
    }

    //工序提交统一接口
    public function customerProcessSubmit(Request $request)
    {
        //获取传入数据
        $input = $request->all();
        $input['process_id'] = isset($input['process_id']) ? $input['process_id'] : '';//订单工序类型
        $input['ordertype_process_id'] = isset($input['ordertype_process_id']) ? $input['ordertype_process_id'] : 0;//订单工序类型关联id
        $input['order_id'] = isset($input['order_id']) ? $input['order_id'] : '';//订单-id
        $input['is_file'] = isset($input['is_file']) ? $input['is_file'] : 0;//是否归档
        $input['is_draft'] = isset($input['is_draft']) ? $input['is_draft'] : 0;//是否存入草稿箱，是的话不校验数据


        //判断是否是归档 || 存放是否归档状态
        if ($input['is_file']) {
            //订单归档信息
            $customerOrderPreObj = CustomerOrderPre::where(['id' => $input['order_id']])->first();
            $customerOrderPreObj->is_file = $input['is_file'];
            $customerOrderPreObj->save();
        }


        //验证字段是必填还是选填 by zzy
        if (!$input['is_draft']) {
            $processFieldList = Process::getFieldListByProcessId($input['process_id']);
            //如果是第一个工序，添加字段‘需完成数量’--功能调整取消这一段

            $processFieldRules = [];
            $processFieldMessage = [];
            foreach ($processFieldList as $key => $val) {
                $isMust = $val['is_must'];
                if ($isMust == 1) {
                    $rulesName = 'required';
                    $fieldName = $val['field_name'];
                    $fieldTitle = $val['title'];
                    $fieldMsg = $fieldName . '.' . $rulesName;
                    $processFieldRules[$fieldName] = $rulesName;
                    $processFieldMessage[$fieldMsg] = $fieldTitle . '必填';

                    $inputValue = $input[$fieldName];
                    if (empty($inputValue)) {
                        xThrow(ERR_PARAMETER, $fieldTitle . '必填');
                    }
                }
            }
        }

        //获取用户id
        $userId = Func::getHeaderValueByName('userid',25);
        $userInfo = DepartmentUser::getCurrentInfo($userId)->toArray();

        $curOrderRow = CustomerOrderPre::where(['id' => $input['order_id']])->first()->toArray();
        $companyId = $curOrderRow['company_id'];

        //获取工序所包含的字段
//        $processFieldList = Process::getFieldArrByProcessId($input['process_id']);
        $processFieldList = Process::getFieldListByProcessId($input['process_id']);

        //数据入库
        //存入印刷工序提交的数据
        $orderProcessPreRow = CustomerOrderProcessPre::firstOrNew(['order_id' => $input['order_id'], 'process_type' => $input['process_id']]);

        $insertRow = [
            'order_id' => $input['order_id'],//关联的订单id
            'process_type' => $input['process_id'],//工序类型
            'ordertype_process_id' => $input['ordertype_process_id'],//工序订单类型关联id
            'company_id' => $companyId,
        ];


        //如果是第一道工序，添加字段需完成数量--功能调整,第一个工序需完成数量取产品的数量
        //调整为所有工序需完成数量都由订单产品数量挂钩

        $orderInfo = CustomerOrderPre::where(['id' => $input['order_id']])->first();
        //获取订单基础信息设置的数量
        $tmpArr = explode(',', $orderInfo['product_num']);
        $productNum = $tmpArr[0];
        if (!$productNum || !is_numeric($productNum)) {
            $productNum = 0;
        }
//        $insertRow['completed_number'] = $productNum;


        //如果是最后一道工序，订单创建完成
        //获取订单信息
        $orderInfo = CustomerOrderPre::where(['id' => $input['order_id']])->first()->toArray();
        $orderType = $orderInfo['order_type'];

        foreach ($processFieldList as $processFieldRow) {

            $processField = $processFieldRow['field_name'];

            //版特殊处理
            if($processFieldRow['field_type'] == 17){
                //限制-版数量想加不能超过产品数量
                $tmpPlateBranch = json_decode(htmlspecialchars_decode($input[$processField]), true);
                $tmpPlateNumAll = 0;

                if(isset($tmpPlateBranch['branch']['colourplate'])){
                    foreach ($tmpPlateBranch['branch']['colourplate'] as $tmpRow){
                        $tmpPlateNumAll += $tmpRow['num'];
                    }
                }

                if($tmpPlateNumAll && ($tmpPlateNumAll > $orderInfo['product_num']) ){
                    return [
                        'code' => 1,
                        'message' => '版支总数量不能超过产品数量',
                    ];
                }

                $tmpObj = \App\Eloquent\Ygt\CreateOrderPlate::firstOrNew(['id'=>'']);
                $tmpInsertRow = [
                    'type' => 1,
                    'relate_id' => $input['order_id'],
                    'field_name' => $processField,
                    'content' => $input[$processField],
                ];

                $tmpObj->fill($tmpInsertRow);
                $tmpObj->save();
                $createOrderPlateId = $tmpObj->id;

                $insertRow[$processField] = $createOrderPlateId;
            }
            else if($processFieldRow['field_type'] == 4){
                $input = OrderEngine::handleInput($input,$processField,$processFieldRow['field_type'],'purchase_info');
                $insertRow[$processField] = $input[$processField];
            }elseif($processFieldRow['field_type'] == 22){//半成品
                $tmpObj = \App\Eloquent\Ygt\CreateOrderProcessProduct::firstOrNew(['id'=>'']);
                $tmpInsertRow = [
                    'type' => 1,
                    'relate_id' => $input['order_id'],
                    'field_name' => $processField,
                    'content' => $input[$processField],
                ];

                $tmpObj->fill($tmpInsertRow);
                $tmpObj->save();
                $createOrderProcessProductId = $tmpObj->id;

                $insertRow[$processField] = $createOrderProcessProductId;
            }
            else{
                $insertRow[$processField] = $input[$processField];
            }
        }

        $orderProcessPreRow->fill($insertRow);
        $orderProcessPreRow->save();

        $orderTypeObj = new OrderType();
        $nextProcessId = $orderTypeObj->getNextOneProcessId($orderType, $input['process_id']);//获取下一个工序
        if ($input['ordertype_process_id']) {//新旧兼容
            $nextOrderTypeProcessRow = $orderTypeObj->getNextStep($input['ordertype_process_id']);//获取下一个工序
            $nextProcessId = $nextOrderTypeProcessRow[0]['process_id'];
            $nextOrdertypeProcessId = $nextOrderTypeProcessRow[0]['id'];
        } else {
            $nextProcessId = $orderTypeObj->getNextOneProcessId($orderType, $input['process_id']);//获取下一个工序
            $nextOrdertypeProcessId = '';
        }


        //保存优先采购信息
        if(isset($input['purchase_info']) && !empty($input['purchase_info'])){
            $purchase_info = $input['purchase_info'];
            foreach($purchase_info as $val){
                OrderMaterialPurchaseMark::updateOrCreate(
                    [
                        'customer_order_pre_id'=>$input['order_id'],
                        'material_id'=>$val['id']
                    ],
                    [
                        'is_purchase'=>$val['is_purchase'],
                    ]
                );
            }
        }

        if ($nextProcessId || $input['is_draft']) {//有下一步或者是退出保存操作
            if ($nextProcessId) {
                $return = [
                    'is_final' => 0, //是否为最后一道工序
                    'message' => '提交成功',//提示信息
                    'next_process_id' => $nextProcessId,//下一道工序的id
                    'next_ordertype_process_id' => $nextOrdertypeProcessId,//下一道工序的工序订单类型关联id
                ];
            } else {
                $return = [
                    'is_final' => 0, //是否为最后一道工序
                    'message' => '提交成功',//提示信息
                ];
            }
        } else {//提交生成正式订单
            $returnInfo = $this->customerOrderCreate($input['order_id']);
            $return = [
                'is_final' => 1,//是否为最后一道工序
                'message' => '创建成功',//提示信息
                'order_id' => $returnInfo['customer_order_id'],//创建成功的订单id
                'order_type' => $orderType,//创建成功的订单工序类型
                'is_single_person' => $returnInfo['is_single_person'],//创建成功的订单工序类型
            ];

            //更新所有相关优先采购记录的customer_order_id zq
            OrderMaterialPurchaseMark::where('customer_order_pre_id','=',$input['order_id'])
                ->whereNull('customer_order_id')
                ->update(['customer_order_id'=>$returnInfo['customer_order_id']]);
        }

        return $return;
    }

    /**
     * Description:正式生成订单数据
     * User: zhuyujun
     * @param $orderPreId
     */
    public function customerOrderCreate($orderPreId)
    {
        $orderId = '';
        //基础信息
        //取出预生成数据
        $orderPre = CustomerOrderPre::where('id', $orderPreId);
        $orderPreRow = $orderPre->first()->toArray();

        //获取登陆用户信息
        $userId = $orderPreRow['uid'];
        $userInfo = DepartmentUser::getCurrentInfo($userId)->toArray();

        $companyId = $orderPreRow['company_id'];

        //存入正式数据
        $order = CustomerOrder::firstOrNew(['id' => '']);
        unset($orderPreRow['id']);//不使用预生成表的id
        unset($orderPreRow['is_trash']);//删除草稿箱表独有的字段
        $orderPreRow['order_pre_id'] = $orderPreId;//存入对应的草稿箱

        ////生成订单号
        //获取该订单是当天的第几单
        $dayStartTime = strtotime(date('Ymd'));
        $intradayOrderCount = CustomerOrder::withTrashed()->where([['created_at', '>=', $dayStartTime]])->get()->count();

        $ordeTitleIndex = '';
        $intradayOrderCount++;
        if ($intradayOrderCount < 10) {
            $ordeTitleIndex = sprintf('0%d', $intradayOrderCount);
        } else {
            $ordeTitleIndex = $intradayOrderCount;
        }
        $orderPreRow['order_title'] = 'DD' . date('ymd') . $ordeTitleIndex;


        $isFile = $orderPreRow['is_file'];//是否归档
        if ($isFile) {
            $orderPreRow['is_deal_price'] = 1;//归档不需要再确定价格
        }

        $order->fill($orderPreRow);
        $order->save();
        $orderId = $order->id;
        $foreignKey = $order->id;
        //删除预生成数据
        //基础信息
        $orderPre->delete();

        //数据加入到订单列表关联表中
        $orderPreRow['id'] = $orderId;
//        OrderEngine::importMainOrder($orderPreRow);

        //工序信息处理
        $orderProcessPreList = CustomerOrderProcessPre::where('order_id', $orderPreId)->get();

        //获取第一道步骤涉及的工序
        $processFirstList = OrderType::getFirstProcessBag($orderPreRow['order_type'])->toArray();


        foreach ($orderProcessPreList as $orderProcessPreObj) {
            $orderProcessPreRow = $orderProcessPreObj->toArray();
            //存入正式数据
            $orderProcess = CustomerOrderProcess::firstOrNew(['id' => '']);
            $orderProcessPreRow['order_id'] = $orderId;
            $orderProcessPreRow['status'] = 1;//订单工序默认状态为，1-待接单 2-确认开工（未领取材料） 3-已领取材料 4-确认完工
            $orderProcess->fill($orderProcessPreRow);
            $orderProcess->save();
            ////添加材料
            //获取字段信息
            $orderProcessPreObj->delete();
        }

        //如果是归档，不需要发送消息 ||增加了订单议价功能，不再直接给下单人发消息 20180615
//        if (!$isFile) {
//            //发送消息给下单人
//            //获取下单人权限列表
//            $appnodeId = 1;//有下单功能
//            $privilegeList = Privilege::getPrivilegeIds($companyId, $appnodeId);
//
//            foreach ($privilegeList as $privilegeId) {
//                //发送消息给下单人
//                $data = [
//                    'company_id' => $companyId,
//                    'privilege_id' => $privilegeId,
//                    'form_user_id' => $userId,
//                    'to_user_id' => '',
//                    'foreign_key' => $foreignKey,
//                    'type' => 16,
//                    'type_id' => $orderId,
//                    'title' => '客户订单',
//                    'content' => '有新的订单'
//                ];
//                UserMessage::sendCustomerOrderMessage($data);
//            }
//        }


        //添加开票表客户订单id
        $customerOrderBillingObj = CustomerOrderBilling::where(['customer_order_pre_id' => $orderPreRow['order_pre_id']])->first();
        if ($customerOrderBillingObj) {
            $customerOrderBillingObj->customer_order_id = $orderId;
            $customerOrderBillingObj->save();
        }


        //新增议价功能 || 归档不需要这个操作20180619

        if (!$isFile) {
            $customerOrderPriceObj = \App\Eloquent\Ygt\CustomerOrderPrice::firstOrNew(['customer_order_id' => $orderId]);

            //获取客户的用户ID
            $customerUserId = \App\Eloquent\Ygt\Customer::where(['id' => $orderPreRow['customer_name']])->first()->user_id;
            $insertRow = [
                'customer_order_id' => $orderId,
                'customer_uid' => $customerUserId,
                'company_id' => $companyId,
                'status' => 1,//状态2 下单人定价格
            ];
            $customerOrderPriceObj->fill($insertRow);
            $customerOrderPriceObj->save();



            ////////////////////////////////////////////// xyz
            //消息内容
            $messageContent = $this->getCustomerOrderRelateMessageContent(
                $orderId,
                [
                    '工艺名称'=>'',
                    '单位名称'=>'',
                    '品名'=>'',
                    '成品规格'=>'',
                    '数量'=>'',
                    '交货日期'=>'',
                    '订单号'=>'',
                ],
                []
            );

            //给销售员角色发送消息 -- 给添加这个客户的销售员发送消息 20180629
            $addUserId = \App\Eloquent\Ygt\Customer::where(['id' => $orderPreRow['customer_name']])->first()->add_user_id;
            $isSeller =  \App\Eloquent\Ygt\Privilege::getAppnodeId($userInfo['privilege_id'], 13);//是否为销售
            if ($addUserId && !$isSeller) {
                $data = [
                    'company_id' => $companyId,
                    'privilege_id' => '',
                    'form_user_id' => $userId,
                    'to_user_id' => $addUserId,
                    'foreign_key' => $orderId,
                    'type' => 19,//type待定
                    'type_id' => $orderId,
                    'title' => $orderPreRow['order_title'],
                    'content' => $messageContent,
                    'theme'=>'客户询单'
                ];
                UserMessage::sendCustomerOrderMessage($data);
            }

//            $privilegeIdList = \App\Engine\OrderEngine::getPrivilegeByNode($companyId,13);
//            foreach ($privilegeIdList as $privilegeId) {
//                if ($privilegeId) {
//                    $data = [
//                        'company_id' => $companyId,
//                        'privilege_id' => $privilegeId,
//                        'form_user_id' => $userId,
//                        'to_user_id' => '',
//                        'foreign_key' => $orderId,
//                        'type' => 19,//type待定
//                        'type_id' => $orderId,
//                        'title' => $orderPreRow['order_title'],
//                        'content' => '有客户下了新订单'
//                    ];
//                    UserMessage::sendCustomerOrderMessage($data);
//                }
//            }
        }

        //判断创建的订单角色有没有下单人权限，有的话需要直接跳转
        //判断用户是否为下单人
//        $privilegeIdList = \App\Engine\OrderEngine::getPrivilegeByNode($companyId, 1);
//        $isSinglePerson = 0;
//        if (in_array($userInfo['privilege_id'], $privilegeIdList)) {
//            $isSinglePerson = 1;
//        }

        //调整为销售员都跳转到报价页面
        $privilegeIdList = \App\Engine\OrderEngine::getPrivilegeByNode($companyId, 13);
        $isSinglePerson = 0;
        if (in_array($userInfo['privilege_id'], $privilegeIdList)) {
            $isSinglePerson = 1;
        }

        return [
            'customer_order_id' => $orderId, //订单ID
            'is_single_person' => $isSinglePerson, //是否需要跳转到订单价格页面 1-是 0-否
        ];
    }

    public function getRelatedFeedbackListByCustomerOrderId(){
        $userId             = Func::getHeaderValueByName('userid');
        $userInfo           = DepartmentUser::getCurrentInfo($userId);
        if(!$userInfo)
        {
            xThrow( ERR_PARAMETER,'登录超时' );
        }


        //获取传入数据
        $customer_order_id = request('customer_order_id');
        $customer_id = request('customer_id',0);
        $page               = request( 'page', 1 );
        $limit              = request('limit', 10 );
        $offset             = ($page - 1) * $limit;

        //获得订单信息
        $CustomerOrderInfo = CustomerOrder::where('id','=',$customer_order_id)->get()->toArray()[0];
        $order_type = $CustomerOrderInfo['order_type'];

        $CustomerOrderFeedbackObj = \App\Eloquent\Ygt\CustomerOrderFeedback
            ::leftJoin('ygt_customer_order','ygt_customer_order_feedback.customer_order_id','=','ygt_customer_order.id')
            ->leftJoin('ygt_user','ygt_customer_order_feedback.uid','=','ygt_user.id')
            ->where('ygt_customer_order.order_type','=',$order_type);

        if($userInfo['company_id'] == 2 && $userInfo['privilege_id'] == 110){
            $CustomerOrderFeedbackObj = $CustomerOrderFeedbackObj->where("ygt_customer_order_feedback.uid",'=',$userId);
        }
        else{
            if($customer_id){
                //获得客户信息
                $customerInfo = Customer::where('id','=',$customer_id)->get()->toArray()[0];
                $CustomerOrderFeedbackObj = $CustomerOrderFeedbackObj->where("ygt_customer_order_feedback.uid",'=',$customerInfo['user_id']);
            }
        }

        $count = $CustomerOrderFeedbackObj->count();

        $customerOrderFeedbackRowList = $CustomerOrderFeedbackObj
            ->limit($limit)->offset($offset)
            ->get(['ygt_customer_order_feedback.*','ygt_user.truename'])->toArray();

        foreach($customerOrderFeedbackRowList as $key=>$customerOrderFeedbackRow){
            $customerOrderFeedbackRowList[$key] = [
                'id'=>$customerOrderFeedbackRow['id'],
                'desc'=>$customerOrderFeedbackRow['desc'],
                'truename'=>empty($customerOrderFeedbackRow['customer_name'])?$customerOrderFeedbackRow['truename']:$customerOrderFeedbackRow['customer_name'],
                'date'=>date('Y-m-d',$customerOrderFeedbackRow['created_at'])
            ];
        }

        $data               = [
            'lists'=>$customerOrderFeedbackRowList
        ];
        $pagingData         = [
            'page'         => $page,
            'pageSize'     => $limit,
            'total'         => $count,
            'total_page'   => ceil($count/$limit),
            'keyword'      => ''
        ];
        return $this->pagingData($data, $pagingData);

    }


    //为工艺获得类似反馈列表
    public function getRelatedFeedbackList(){
        $userId             = Func::getHeaderValueByName('userid');
        $userInfo           = DepartmentUser::getCurrentInfo($userId);
        if(!$userInfo)
        {
            xThrow( ERR_PARAMETER,'登录超时' );
        }

        //获取传入数据
        $order_type = request('order_type');
        $customer_id = request('customer_id',0);
        $page               = request( 'page', 1 );
        $limit              = request('limit', 10 );
        $offset             = ($page - 1) * $limit;

        $CustomerOrderFeedbackObj = \App\Eloquent\Ygt\CustomerOrderFeedback
            ::leftJoin('ygt_customer_order','ygt_customer_order_feedback.customer_order_id','=','ygt_customer_order.id')
            ->leftJoin('ygt_user','ygt_customer_order_feedback.uid','=','ygt_user.id')
            ->where('ygt_customer_order.order_type','=',$order_type);

        if($userInfo['company_id'] == 2 && $userInfo['privilege_id'] == 110){
            $CustomerOrderFeedbackObj = $CustomerOrderFeedbackObj->where("ygt_customer_order_feedback.uid",'=',$userId);
        }
        else{
            if($customer_id){
                //获得客户信息
                $customerInfo = Customer::where('id','=',$customer_id)->get()->toArray()[0];
                $CustomerOrderFeedbackObj = $CustomerOrderFeedbackObj->where("ygt_customer_order_feedback.uid",'=',$customerInfo['user_id']);
            }
        }

        $count = $CustomerOrderFeedbackObj->count();

        $customerOrderFeedbackRowList = $CustomerOrderFeedbackObj
            ->limit($limit)->offset($offset)
            ->get(['ygt_customer_order_feedback.*','ygt_user.truename'])->toArray();

        foreach($customerOrderFeedbackRowList as $key=>$customerOrderFeedbackRow){
            $customerOrderFeedbackRowList[$key] = [
                'id'=>$customerOrderFeedbackRow['id'],
                'desc'=>$customerOrderFeedbackRow['desc'],
                'truename'=>empty($customerOrderFeedbackRow['customer_name'])?$customerOrderFeedbackRow['truename']:$customerOrderFeedbackRow['customer_name'],
                'date'=>date('Y-m-d',$customerOrderFeedbackRow['created_at'])
            ];
        }

        $data               = [
            'lists'=>$customerOrderFeedbackRowList
        ];
        $pagingData         = [
            'page'         => $page,
            'pageSize'     => $limit,
            'total'         => $count,
            'total_page'   => ceil($count/$limit),
            'keyword'      => ''
        ];
        return $this->pagingData($data, $pagingData);
    }


    //获得订单反馈信息
    public function getFeedbackList(){
        $userId             = Func::getHeaderValueByName('userid');
        $userInfo           = DepartmentUser::getCurrentInfo($userId);
        if(!$userInfo)
        {
            xThrow( ERR_PARAMETER,'登录超时' );
        }

        //获取传入数据
        $customerOrderId = request('customer_order_id');
        $page               = request( 'page', 1 );
        $limit              = request('limit', 10 );
        $offset             = ($page - 1) * $limit;

        $count = \App\Eloquent\Ygt\CustomerOrderFeedback::where(['customer_order_id'=>$customerOrderId])->orderByDesc('id')->leftJoin('ygt_user','ygt_customer_order_feedback.uid','=','ygt_user.id')
            ->count();

        $customerOrderFeedbackRowList = \App\Eloquent\Ygt\CustomerOrderFeedback::where(['customer_order_id'=>$customerOrderId])->orderByDesc('id')->leftJoin('ygt_user','ygt_customer_order_feedback.uid','=','ygt_user.id')
            ->limit($limit)->offset($offset)
            ->get(['ygt_customer_order_feedback.*','ygt_user.truename'])->toArray();



        //$customerOrderFeedbackRowList = \App\Eloquent\Ygt\CustomerOrderFeedback::where(['customer_order_id'=>$customerOrderId])->orderByDesc('id')->get()->toArray();
        foreach($customerOrderFeedbackRowList as $key=>$customerOrderFeedbackRow){
            $customerOrderFeedbackRowList[$key] = [
                'id'=>$customerOrderFeedbackRow['id'],
                'desc'=>$customerOrderFeedbackRow['desc'],
                'truename'=>empty($customerOrderFeedbackRow['customer_name'])?$customerOrderFeedbackRow['truename']:$customerOrderFeedbackRow['customer_name'],
                'date'=>date('Y-m-d',$customerOrderFeedbackRow['created_at'])
            ];
        }

        $data               = [
            'lists'=>$customerOrderFeedbackRowList
        ];
        $pagingData         = [
            'page'         => $page,
            'pageSize'     => $limit,
            'total'         => $count,
            'total_page'   => ceil($count/$limit),
            'keyword'      => ''
        ];
        return $this->pagingData($data, $pagingData);
    }


    //订单详情
    public function getCustomerOrderDetail()
    {
        $userId             = Func::getHeaderValueByName('userid',25);
        $userInfo           = DepartmentUser::getCurrentInfo($userId);
        if(!$userInfo)
        {
            xThrow( ERR_PARAMETER,'登录超时' );
        }
        $isManager          = Privilege::getAppnodeId($userInfo['privilege_id'], 1);//是否为下单人（管理员权限）
        $isSeller          = Privilege::getAppnodeId($userInfo['privilege_id'], 13);//是否为销售（管理员权限）

        $isCustomer = 0;
        if($userInfo['company_id'] == 2){
            $isCustomer = 1;
        }

//        $lookOrderButton    = $isManager ? 1 : 0;//订单查看相关工单,只需要下单人有这个查看权限
        $lookOrderButton    = 1;//都可以查相关工单

        //获取传入数据
        $customerOrderId = request('customer_order_id');
        $input['order_id'] = $customerOrderId;//订单-id

        //获取订单信息
        $orderInfo = CustomerOrder::where('id', $input['order_id'])->first()->toArray();
        //组建基本信息
        $tmpCustomerOrderRow = $orderInfo;
            //获取生产实例图
            $productionCaseDiagramIds = isset($tmpCustomerOrderRow['production_case_diagram']) ? $tmpCustomerOrderRow['production_case_diagram'] : '';
            if ($productionCaseDiagramIds) {
                $tmpArr = explode(',', $productionCaseDiagramIds);
                $productionCaseDiagramId = reset($tmpArr);
                $productionCaseDiagram = ImgUpload::getImgUrlById($productionCaseDiagramId);
                if (!$productionCaseDiagram) {//未获取到id对应的图片
                    $productionCaseDiagram = env('APP_URL') . '/assets/mobile/common/images/order_list_default.png';
                }

            } else {
                $productionCaseDiagram = env('APP_URL') . '/assets/mobile/common/images/order_list_default.png';
            }

            //订单创建时间（派发时间）
            $tmpArr = $tmpCustomerOrderRow;
            $orderCreateTime = $tmpArr['created_at'];

            if ($orderCreateTime) {
                $orderCreateTime = date('Y-m-d', $orderCreateTime);
                if ($orderCreateTime < 631152000) {//过滤1970的情况
                    $orderCreateTime = '';
                }
            } else {
                $orderCreateTime = '';
            }

            //订单字段处理
            $tmpCustomerOrderRow = \App\Engine\OrderEngine::dealOrderFiled($tmpCustomerOrderRow);


            //订单状态
            $statusColor = 'FE7E57';//默认颜色
            if (!$tmpCustomerOrderRow['is_deal_price']) {
                //订单价格未确认
                $customerOrderPriceObj = \App\Eloquent\Ygt\CustomerOrderPrice::where(['customer_order_id' => $tmpCustomerOrderRow['id']])->first();
                if ($customerOrderPriceObj) {
                    $customerOrderPriceStatus = $customerOrderPriceObj->status;
                    $customerOrderPriceStatusArr = config('order.customer_order_price_status_list');
                    if (isset($customerOrderPriceStatusArr[$customerOrderPriceStatus])) {
                        $orderStatus = $customerOrderPriceStatusArr[$customerOrderPriceStatus]['txt'];
                        $statusColor = $customerOrderPriceStatusArr[$customerOrderPriceStatus]['color'];
                    } else {
                        $orderStatus = '';
                    }
                    $type = 2;
                } else {
                    $orderStatus = '';
                    $type = 1;
                }

            } else {
                //订单价格已确认
                $customerOrderStatusList = config('order.customer_order_status_list');
                if (isset($customerOrderStatusList[$tmpCustomerOrderRow['status']])) {
                    $orderStatus = $customerOrderStatusList[$tmpCustomerOrderRow['status']]['txt'];
                    $statusColor = $customerOrderStatusList[$tmpCustomerOrderRow['status']]['color'];

                }

                $type = 1;

            }

            //针对单下单人权限 强制更改订单状态文字
            if($isManager && !$isSeller){
                if(in_array($tmpCustomerOrderRow['status'],[1,2,3])){
                    $orderStatus = '';
                }

                if(in_array($tmpCustomerOrderRow['status'],[5,6])){
                    $orderStatus = '已报价';
                }
            }

            if($tmpCustomerOrderRow['is_file'] == 1){
                $orderStatus = '已归档';
            }

            //获取工序类型名称
            $orderTypeTitle = OrderType::getOneValueById($tmpCustomerOrderRow['order_type'], 'title');

            $productName = \App\Engine\OrderEngine::getOrderFiledValueTrue($tmpCustomerOrderRow['product_name'], 20);

            //追加图片ID
            $imgId = $tmpCustomerOrderRow['production_case_diagram'];

            $tmpCustomerOrderRow['order_title'] = \App\Engine\Common::changeSnCode($tmpCustomerOrderRow['order_title']);
            $orderInfoTemp = [
                'ordertype_title' => '工艺:',//工单列表展示字段
                'order_title' => '单号:',//工单列表展示字段
                'unit_name' => isset($tmpCustomerOrderRow['field_name_23']) ? $tmpCustomerOrderRow['field_name_23'] : '',//新加字段单位
                'product_name' => isset($productName) ? $productName : '',//新加字段品名
                'order_title_value' => $tmpCustomerOrderRow['order_title'],//新加字段单号
                'firstPropertyName' => '成品规格',
                'secondPropertyName' => '数量',
                'thirdPropertyName' => '交货日期',
                'thirdPropertyValue' => $tmpCustomerOrderRow['finished_date'],
                'secondPropertyValue' => $tmpCustomerOrderRow['product_num'],
                'firstPropertyValue' => isset($tmpCustomerOrderRow['finished_specification']) ? $tmpCustomerOrderRow['finished_specification'] : '',
                'productionCaseDiagram' => $productionCaseDiagram,
                'productOrderTimeValue' => $orderCreateTime,
                'orderTypeTitle' => $orderTypeTitle,
                'relate_id' => $tmpCustomerOrderRow['id'],
                'orderStatus' => $orderStatus,
                'statusColor' => $statusColor,
                'type' => $type,
                'img_id' => $imgId,
            ];
        //获取顾客名
        $orderInfoTemp['truename'] = Customer::getOneValueById($orderInfo['customer_name'],'customer_name');

        //获取价格信息
        $customerOrderPriceInfo = CustomerOrderPrice::where('customer_order_id','=',$tmpCustomerOrderRow['id'])->first();
        if($customerOrderPriceInfo){
            $customerOrderPriceInfo = $customerOrderPriceInfo->toArray();
        }
        $productNumArr = explode(',',$orderInfo['product_num']);
        $tempUnit = '';
        if(count($productNumArr) == 2){
            $tempUnit = $productNumArr[1];
        }

        //订单成本价
        if($customerOrderPriceInfo['singleperson_price'] == 'null' || !$customerOrderPriceInfo['singleperson_price']){
            $orderInfoTemp['singleperson_price'] = $customerOrderPriceInfo['deal_price'].'元/'.$tempUnit;
        }
        else{
            $orderInfoTemp['singleperson_price'] = $customerOrderPriceInfo['singleperson_price'].'元/'.$tempUnit;
        }

        //销售价
        if($customerOrderPriceInfo['deal_price'] == 'null'){
            $orderInfoTemp['deal_price'] = '元/'.$tempUnit;
        }
        else{
            $orderInfoTemp['deal_price'] = $customerOrderPriceInfo['deal_price'].'元/'.$tempUnit;
        }

        //发货方式
        $orderInfoTemp['delivery'] = '工厂发货';

        //获取工单信息
        $g_orderInfo = Order::where('customer_order_id')->orderBy('id','desc')->first()->toArray();
        //总数
        $temp_total_number = $productNumArr[0];
        //已完成数量
        $temp_already_finished_number = 0;
        //已交货数量
        $temp_already_send_number = 0;
        //生产中
        $temp_producing_number = 0;
        //未生产
        $temp_not_produce_number = $temp_total_number;
        if(!empty($g_orderInfo)){
            $temp_warehouse_info = Warehouse::where('order_id','=',$g_orderInfo['id'])->first();
            if($temp_warehouse_info){
                $temp_warehouse_info = $temp_warehouse_info->toArray();
                $temp_already_finished_number = $temp_warehouse_info['all_number'];
                $temp_already_send_number = $temp_already_finished_number-$temp_warehouse_info['now_number'];
            }

            //获取第一条工序
            $temp_first_order_process_info = OrderProcess::where('order_id','=',$g_orderInfo['id'])->first();
            if($temp_first_order_process_info){
                $temp_first_order_process_info = $temp_first_order_process_info->toArray();
                $temp_producing_number = $temp_first_order_process_info['completed_number']-$temp_already_finished_number;
                $temp_not_produce_number = $temp_total_number-$temp_first_order_process_info['completed_number'];
            }
        }


        //完成数量信息
        $orderInfoTemp['number_list'] = [
            [
                'title'=>'生产中',
                'number'=>$temp_producing_number.$tempUnit
            ],
            [
                'title'=>'已交货',
                'number'=>$temp_already_send_number.$tempUnit
            ],
            [
                'title'=>'已完成',
                'number'=>$temp_already_finished_number.$tempUnit
            ],
            [
                'title'=>'未生产',
                'number'=>$temp_not_produce_number.$tempUnit
            ]
        ];


        //圆形图信息 zq
        //追加工单进度情况
        $progressBar = [];
        //获取工单对应的所有工序
        $tmpOrderProcessList = \App\Engine\OrderType::getAllOrderTypeProcess($tmpCustomerOrderRow['order_type'])->toArray();
        foreach ($tmpOrderProcessList as $tmpProcessId) {
            $tmpProcessTitle = \App\Eloquent\Ygt\Process::getOneValueById($tmpProcessId, 'title');

            //工序完成度
            if(!empty($g_orderInfo)){
                $tmpOrderProcessRow = OrderProcess::where(['order_id' => $g_orderInfo['id'], 'process_type' => $tmpProcessId])->first();
                if (!$tmpOrderProcessRow) {
                    continue;
                }
                $tmpOrderProcessNeedNum =\App\Engine\OrderEngine::getOrderPorcessNeedNum($tmpOrderProcessRow['process_type'],$g_orderInfo);//需完成数量
                $tmpRadio = 0;
                if($tmpOrderProcessNeedNum){
                    $tmpRadio = $tmpOrderProcessRow['completed_number'] / $tmpOrderProcessNeedNum;
                }
                $tmpRadio = sprintf('%.2f',$tmpRadio);
                $tmpType = \App\Engine\OrderEngine::getOrderRadioType($tmpRadio);

                $progressBar[] = [
                    'type' => $tmpType,
                    'radio' => $tmpRadio,
                    'title' => $tmpProcessTitle,
                ];
            }
            else{
                $progressBar[] = [
                    'type' => 1,
                    'radio' => 0.00,
                    'title' => $tmpProcessTitle,
                ];
            }
        }
        $orderInfoTemp['progressBar'] = $progressBar;

        $orderInfoTemp['draw_type'] = 1;
        if($isSeller){
            $orderInfoTemp['draw_type'] = 1;
        }
        else if($isManager){
            $orderInfoTemp['draw_type'] = 2;
        }
        else if($isCustomer){
            $orderInfoTemp['draw_type'] = 3;
        }

        //订单基础信息字段，目前格式固定 -- 已调整为后台控制 20180131
        $userId = Func::getHeaderValueByName('userid',25);
        $userInfo = DepartmentUser::getCurrentInfo($userId)->toArray();

        $companyId = $orderInfo['company_id'];
        $orderBaseFieldList = OrderFieldCompany::getActiveFieldList($companyId);

        $listAll = [];

        //获得订单的价格信息
        $priceInfoList = [];
        $cusomterOrderPriceInfo = CustomerOrderPrice::where('customer_order_id','=',$customerOrderId)->first();
        if($cusomterOrderPriceInfo){
            $cusomterOrderPriceInfo = $cusomterOrderPriceInfo->toArray();
            $priceInfoList[] = [
                'leftLabelValue' => '单价',
                'rightLabelValue' => '￥'.$cusomterOrderPriceInfo['deal_price']
            ];
            $priceInfoList[] = [
                'leftLabelValue' => '版费',
                'rightLabelValue' => $cusomterOrderPriceInfo['edition_fee'].'元'
            ];
            $priceInfoList[] = [
                'leftLabelValue' => '运费',
                'rightLabelValue' => $cusomterOrderPriceInfo['freight_fee'].'元'
            ];
            $priceInfoList[] = [
                'leftLabelValue' => '税点',
                'rightLabelValue' => $cusomterOrderPriceInfo['tax_point'].'%'
            ];
        }

        $baseInfoList = [];
        //基本信息先固定

        $imageList = [];
        $buyersInvoiceId = '';
        if ($orderInfo['production_case_diagram']) {
            $imageIdList = explode(',', $orderInfo['production_case_diagram']);
            foreach ($imageIdList as $imageId) {
                $imageUrl = ImgUpload::getImgUrlById($imageId, true, false);
                $imageList[] = $imageUrl;
            }
        }
        $customerAddressArr = [];
        $textArr = [];
        foreach ($orderBaseFieldList as $key => $row) {
            $leftLabelValue = $row['title'];
            $rightLabelValue = $orderInfo[$row['field_name']];
            if ($row['field_type'] == 9) {//图片处理
                //如果有上传的图片地址，存入数组中
                continue;//另外处理
            } elseif ($row['field_type'] == 8) {//配送地址 处理
                //continue;//另外处理
                $addressWhere = ['id' => $rightLabelValue];
//                $customerAddress = CustomerAddress::getInfo($addressWhere);
                $customerAddress = \App\Eloquent\Ygt\BuyersAddress::withTrashed()->where($addressWhere)->first();
                if ($customerAddress) {
                    $customerAddressArr = $customerAddress->toArray();
                }
                continue;
            } elseif ($row['field_type'] == 21) {//开票资料另外处理
                $buyersInvoiceId = $orderInfo[$row['field_name']];
                continue;
            }elseif ($row['field_type'] == 2) {//文本域类型的字段另外处理
                $rightLabelValue = OrderEngine::getOrderFiledValueTrue($orderInfo[$row['field_name']], $row['field_type']);
                $textArr[] = [
                    'leftLabelValue' => $leftLabelValue,
                    'rightLabelValue' => $rightLabelValue
                ];
                continue;
            }


            $rightLabelValue = OrderEngine::getOrderFiledValueTrue($orderInfo[$row['field_name']], $row['field_type']);

            $baseInfoList[] = [
                'leftLabelValue' => $leftLabelValue,
                'rightLabelValue' => $rightLabelValue
            ];
        }
        if (!empty($customerAddressArr)) {
            $baseInfoList[] = [
                'leftLabelValue' => '收货人',
                'rightLabelValue' => $customerAddressArr['consignee']
            ];
            $baseInfoList[] = [
                'leftLabelValue' => '联系手机',
                'rightLabelValue' => $customerAddressArr['phone']
            ];
            $baseInfoList[] = [
                'leftLabelValue' => '区县地址',
                'rightLabelValue' => $customerAddressArr['province_name'] . ' ' . $customerAddressArr['city_name'] . ' ' . $customerAddressArr['area_name']
            ];
            $baseInfoList[] = [
                'leftLabelValue' => '详细地址',
                'rightLabelValue' => $customerAddressArr['address']
            ];
        }

        $list1 = [];
        $customerInvoiceRow = \App\Eloquent\Ygt\BuyersInvoice::where(['id' => $buyersInvoiceId])->first();
        if ($customerInvoiceRow) {
            $list1 = [
                [
                    'leftLabelValue' => '账户名称',
                    'rightLabelValue' => $customerInvoiceRow['account_name'],
                ],
                [
                    'leftLabelValue' => '纳税人识别号',
                    'rightLabelValue' => $customerInvoiceRow['taxpayer_number'],
                ],
                [
                    'leftLabelValue' => '省市区',
                    'rightLabelValue' => $customerInvoiceRow['province_name'] . $customerInvoiceRow['city_name'] . $customerInvoiceRow['area_name'],
                ],
                [
                    'leftLabelValue' => '详细地址',
                    'rightLabelValue' => $customerInvoiceRow['address'],
                ],
                [
                    'leftLabelValue' => '电话',
                    'rightLabelValue' => $customerInvoiceRow['telphone'],
                ],
                [
                    'leftLabelValue' => '开户行',
                    'rightLabelValue' => $customerInvoiceRow['opening_bank'],
                ],
                [
                    'leftLabelValue' => '银行卡号',
                    'rightLabelValue' => $customerInvoiceRow['bank_card_number'],
                ],
            ];

        }

        $baseInfoList = array_merge($priceInfoList, $baseInfoList);
        $baseInfoList = array_merge($baseInfoList, $list1);
        $baseInfoList = array_merge($baseInfoList, $textArr);

        $listAll[] = [
            'titleLabelValue' => '基本信息',
            'list' => $baseInfoList,
            'listImageList' => [],
        ];

        //动态获取工序数据
        //获取订单对应的所有工序
        $orderProcessList = OrderType::getAllOrderTypeProcess($orderInfo['order_type']);
        foreach ($orderProcessList as $processId) {
            //获取工序信息
            $orderProcessInfo = CustomerOrderProcess::where(['order_id' => $orderInfo['id'], 'process_type' => $processId])->first()->toArray();
            $processTitle = Process::getOneValueById($orderProcessInfo['process_type'], 'title');

            $list = [];
            //通过字段类型不同处理
            //获取字段对应的类型1=>'文本',2=>'文本域',3=>'下拉框-跳界面',4=>'跳材料',5=>'有单位',6=>'开关',7=>'时间'
            $processFieldList = Process::getFieldListByProcessId($orderProcessInfo['process_type']);
            foreach ($processFieldList as $processFieldRow) {
                $tmpFiledType = $processFieldRow['field_type'];
                $showTitle = $orderProcessInfo[$processFieldRow['field_name']];//默认展示字段的内容
                if ($tmpFiledType == 4) {//材料
                    //显示每种材料
                    $materialIdList = explode(',', $orderProcessInfo[$processFieldRow['field_name']]);
                    foreach ($materialIdList as $materialId) {
                        if ($materialId) {
                            //获取材料信息（名称）
                            $materialObj = ProductEngine::getProductInfo($materialId);
                            $materialName = $materialId;
                            if ($materialObj) {
                                $materialName = $materialObj->product_name;
                            }

                            $list[] = [
                                'leftLabelValue' => $processFieldRow['title'],
                                'rightLabelValue' => $materialName,
                            ];
                        }
                    }
                    continue;
                }


                if ($tmpFiledType == 17 && $orderProcessInfo[$processFieldRow['field_name']]) {
                    $tmpCreateOrderPlateId = $orderProcessInfo[$processFieldRow['field_name']];
                    $tmpCreateOrderPlateRow = \App\Eloquent\Ygt\CreateOrderPlate::where(['id'=>$tmpCreateOrderPlateId])->first();
                    $tmpCreateOrderPlateRowContent =json_decode(htmlspecialchars_decode($tmpCreateOrderPlateRow['content']), true);
                    //显示固定版、套版组合
                    if(isset($tmpCreateOrderPlateRowContent['branch']['fixed_plate'])){
                        $tmpReList = \App\Engine\OrderEngine::getOrderPlateDealInfo($tmpCreateOrderPlateRowContent,$processFieldRow['title']);
                        foreach ($tmpReList as $tmpReRow){
                            $list[] = [
                                'leftLabelValue' => $tmpReRow['$leftLabelValue'],
                                'rightLabelValue' => $tmpReRow['$rightLabelValue'],
                            ];
                        }
                    }
                }elseif($tmpFiledType == 22 && $orderProcessInfo[$processFieldRow['field_name']]){
                    $tmpCreateOrderProcessProductId = $orderProcessInfo[$processFieldRow['field_name']];
                    $tmpCreateOrderProcessProductRow = \App\Eloquent\Ygt\CreateOrderProcessProduct::where(['id'=>$tmpCreateOrderProcessProductId])->first();
                    $tmpCreateOrderProcessProductRowContent =json_decode(htmlspecialchars_decode($tmpCreateOrderProcessProductRow['content']), true);
                    if($tmpCreateOrderProcessProductRowContent){
                        //显示半成品信息
                        foreach ($tmpCreateOrderProcessProductRowContent as $tmpCreateOrderProcessProductRowContentRow){
                            $list[] = [
                                'leftLabelValue' => $processFieldRow['title'],
                                'rightLabelValue' => "【{$tmpCreateOrderProcessProductRowContentRow['number']}】{$tmpCreateOrderProcessProductRowContentRow['process_product_title']}",
                            ];
                        }
                    }

                }
                else{
                    $showTitle = OrderEngine::getOrderFiledValueTrue($orderProcessInfo[$processFieldRow['field_name']], $tmpFiledType);

                    $list[] = [
                        'leftLabelValue' => $processFieldRow['title'],
                        'rightLabelValue' => $showTitle,
                    ];
//                    $apeList[] = [
//                        '$leftLabelValue' => $processFieldRow['title'],
//                        '$rightLabelValue' => $showTitle,
//                    ];
                }

            }

            $listAll[] = [
                'titleLabelValue' => $processTitle,
                'list' => $list,
                'listImageList' => [],
            ];
        }


        $allowCustomerOrderToOrder = 0; //是否允许创建工单 1-允许 0-不允许
        //判断是否有权限订单转订单
        $isManager = Privilege::getAppnodeId($userInfo['privilege_id'], 1);//是否为下单人（管理员权限）
        if ($isManager) {
            $allowCustomerOrderToOrder = 1;

            ////允许订单多次创建工单 20180620
//            //如果订单已经转过工单，不允许再创建工单
//            $orderCount = Order::where(['customer_order_id' => $customerOrderId])->count();
//            if ($orderCount) {
//                $allowCustomerOrderToOrder = 0;
//            } else {
//                $allowCustomerOrderToOrder = 1;
//            }

            //如果订单归档，不能创建工单
            if ($orderInfo['is_file']) {
                $allowCustomerOrderToOrder = 0;
            }
        }

        $allowCopyCustomerOrder = 0;
        //判断是否可以再来一单，销售员和客商可以再来一单
        //判断用户是否为销售员
        $isSalesperson = \App\Eloquent\Ygt\Privilege::getAppnodeId($userInfo['privilege_id'], 13);//是否为销售员
        if ($userInfo['privilege_id'] == 110 || $isSalesperson) {
            $allowCopyCustomerOrder = 1;
        }


        //如果设置了不能客户创建订单，不能再来一单
        if($userInfo['privilege_id'] == 110){
            //获取客户信息
            $customerInfo = \App\Eloquent\Ygt\Customer::where(['id' => $orderInfo['customer_name']])->first();
            if($customerInfo['is_add_order']){
                $allowCopyCustomerOrder = 1;
            }else{
                $allowCopyCustomerOrder = 0;
            }
        }

        
        ////增加订单反馈信息&是否有反馈按钮 zhuyujun 20180807
        $feedback = '';
        $customerOrderFeedbackRowList = \App\Eloquent\Ygt\CustomerOrderFeedback::where(['customer_order_id'=>$customerOrderId])->orderByDesc('id')->get()->toArray();
        foreach($customerOrderFeedbackRowList as $key=>$customerOrderFeedbackRow){
            if(empty($feedback)){
               $feedback = $customerOrderFeedbackRow['desc'];
            }

            $customerOrderFeedbackRowList[$key] = [
                'id'=>$customerOrderFeedbackRow['id'],
                'desc'=>$customerOrderFeedbackRow['desc'],
                'date'=>date('Y-m-d',$customerOrderFeedbackRow['created_at'])
            ];
        }

        //客商允许反馈订单
        $allowCustomerOrderFeedback = 0;
        if ($userInfo['privilege_id'] == 110) {
            $allowCustomerOrderFeedback = 1;
        }

        $returnApe = [
            'allowCustomerOrderToOrder' => $allowCustomerOrderToOrder,//是否允许订单转工单 1-可以 0-禁止
            'allowCopyCustomerOrder' => $allowCopyCustomerOrder,//是否允许再来一单 1-可以 0-禁止
            'allowCustomerOrderFeedback' => $allowCustomerOrderFeedback,//是否允许反馈信息 1-可以 0-禁止
            'customer_order_id' => $customerOrderId,
            'imageList' => $imageList,
            'listAll' => $listAll,
            'feedback' => $feedback,
            'feedbackList'=>$customerOrderFeedbackRowList,
            'look_order_button'=> $lookOrderButton,
            'base_info'=>$orderInfoTemp
        ];

        return $returnApe;
    }

    //订单转工单
    public function customerOrderToOrder()
    {
        $userId = Func::getHeaderValueByName('userid');
        $userInfo = DepartmentUser::getCurrentInfo($userId)->toArray();

        $customerOrderId = request('customer_order_id');

        //订单基础信息导入到订单表（草稿箱）中
        $customerOrderRow = CustomerOrder::where(['id' => $customerOrderId])->first()->toArray();

        $orderPreObj = OrderPre::firstOrNew(['id' => '']);

        //过滤不需要的字段
        unset($customerOrderRow['is_file']);
        unset($customerOrderRow['order_pre_id']);
        unset($customerOrderRow['is_deal_price']);

        //字段调整
        $customerOrderRow['uid'] = $userId;
        $customerOrderRow['customer_order_id'] = $customerOrderId;

        $orderPreObj->fill($customerOrderRow);
        $orderPreObj->save();
        $orderId = $orderPreObj->id;

        //订单工序信息导入到订单表（草稿箱）中
        $customerOrderProcessList = CustomerOrderProcess::where(['order_id' => $customerOrderId])->get()->toArray();
        foreach ($customerOrderProcessList as $tmpCustomerOrderProcessRow) {
            //字段调整
            unset($tmpCustomerOrderProcessRow['id']);
            $tmpCustomerOrderProcessRow['order_id'] = $orderId;

            $orderProcessPreObj = OrderProcessPre::firstOrNew(['id' => '']);
            $orderProcessPreObj->fill($tmpCustomerOrderProcessRow);
            $orderProcessPreObj->save();
        }

        //更新相关优先采购记录信息
        OrderMaterialPurchaseMark::where('customer_order_id','=',$customerOrderId)
            ->whereNull('order_pre_id')
            ->update(['order_pre_id'=>$orderId]);

        return ['order_id' => $orderId];
    }


    //订单开票
    public function customerOrderBillingInfo()
    {
        $payTypeList = [
            [
                'id' => 1,
                'name' => '现金',
            ],
            [
                'id' => 2,
                'name' => '汇款',
            ],
            [
                'id' => 3,
                'name' => '承兑汇票',
            ]
        ];

        $re = [
            'payTypeList' => $payTypeList,
        ];

        return $re;
    }


    //订单开票-数据提交
    public function customerOrderBillingSubmit()
    {
        $money = request('money') ? request('money') : 0; //金额
        $bank = request('bank'); //开户银行
        $bank_number = request('bank_number'); //银行账号
        $pay_type = request('pay_type'); //支付方式
        $collection_days = request('collection_days');//收款日期
        $customerOrderId = request('order_id');//收款日期
        $img = request('img'); //附件图片，图片id
        $invoiceId = request('invoice_id'); //关联的开票资料id

        if (!$invoiceId) {
            return [
                'code' => 1,
                'message' => '请选择开票资料'
            ];
        }


        //生成一个新的客户订单id -- 不是再来一单的情况下
        if (!$customerOrderId) {
            $customerOrderObj = CustomerOrderPre::firstOrNew(['id' => '']);
            $customerOrderObj->save();
            $customerOrderId = $customerOrderObj->id;
        }

        $customerOrderBillingObj = CustomerOrderBilling::firstOrNew(['id' => $customerOrderId]);
        $insertRow = [
            'customer_order_pre_id' => $customerOrderId,
            'money' => $money,
            'bank' => $bank,
            'bank_number' => $bank_number,
            'pay_type' => $pay_type,
            'collection_days' => $collection_days,
            'img' => $img,
            'invoice_id' => $invoiceId,
        ];
        $customerOrderBillingObj->fill($insertRow);
        $customerOrderBillingObj->save();

        $re = [
            'customer_order_id' => $customerOrderId,//客户订单id
        ];

        return $re;
    }

    //订单再来一单，获取开票消息等基础信息
    public function copyCustomerOrderFirst()
    {
        $userId = Func::getHeaderValueByName('userid');
        $userInfo = DepartmentUser::getCurrentInfo($userId)->toArray();

        $copyOrderId = request('copy_order_id'); //复制订单id

        //旧工单消息
        $copyCustomerOrderRow = CustomerOrder::where(['id' => $copyOrderId])->first();
        if ($copyCustomerOrderRow) {
            $copyCustomerOrderRow = $copyCustomerOrderRow->toArray();
        } else {
            $copyCustomerOrderRow = '';
        }

        $companyId = '';//默认选择的工厂id
        $companyName = '';//默认选择的工厂名称
        $needBilling = 0;//是否开票 0-不开票，1-开票
        $money = '';//金额
        $bank = '';//开户银行
        $bankNumber = '';//银行账号
        $payType = '';//支付方式
        $collectionDays = '';//收款日期
        $imgId = '';//图片id
        $imgUrl = '';//图片地址
        $invoiceId = '';//关联的开票资料id
        $invoiceName = '';

        if ($copyCustomerOrderRow) {
            //默认厂id,名称
            $companyId = $copyCustomerOrderRow['company_id'];
            $companyName = Company::getOneValueById($companyId, 'title');

            //默认是否开票
            //默认开票信息
            $customerOrderBillingRow = CustomerOrderBilling::where(['customer_order_id' => $copyOrderId])->first();
            if ($customerOrderBillingRow) {
                $needBilling = 1;
                $customerOrderBillingRow = $customerOrderBillingRow->toArray();
                $money = $customerOrderBillingRow['money'];
                $bank = $customerOrderBillingRow['bank'];
                $bankNumber = $customerOrderBillingRow['bank_number'];
                $payType = $customerOrderBillingRow['pay_type'];
                $collectionDays = $customerOrderBillingRow['collection_days'];

                $imgId = $customerOrderBillingRow['img'];
                if ($imgId) {
                    $imgIdArr = explode(',', $imgId);
                    foreach ($imgIdArr as $tmpImgId) {
                        if (!trim($tmpImgId)) {//过滤空格 图片id应该不会有0
                            continue;
                        }
                        $tmpImgUrl = ImgUpload::getImgUrlById($tmpImgId);
                        $imgUrl .= $tmpImgUrl . ',';
                    }

                    $imgUrl = trim($imgUrl, ',');
                }

                $invoiceId = $customerOrderBillingRow['invoice_id'];
                $customerInvoiceObj = CustomerInvoice::where(['id' => $invoiceId])->first();
                if ($customerInvoiceObj) {
                    $invoiceName = $customerInvoiceObj->account_name;
                }

            }

            //创建预生成订单&返回预生成订单id
            $customerOrderPreRow = CustomerOrderPre::firstOrNew(['id' => '']);

            $orderType = $copyCustomerOrderRow['order_type'];
//            $userId = $copyCustomerOrderRow['uid'];//再来一单，算当前用户创建的
            $customerId = $copyCustomerOrderRow['customer_name'];

            $companyId = OrderType::getOneValueById($orderType, 'company_id');
            $insertRow = [
                'order_type' => $orderType,
                'order_title' => '',
                'uid' => $userId,
                'company_id' => $companyId,
                'is_trash' => 1,//默认设置为该记录为可删除
//            'is_file' => $isFile,//是否归档
                'customer_name' => $customerId,//客户id
            ];
            $customerOrderPreRow->fill($insertRow);
            $customerOrderPreRow->save();
            $orderId = $customerOrderPreRow->id;
        } else {
            return [
                'code' => 1,
                'message' => '参数出错了'
            ];
        }

        $re = [
            'company_id' => $companyId,
            'company_name' => $companyName,
            'need_billing' => $needBilling,
            'money' => $money,
            'bank' => $bank,
            'bank_number' => $bankNumber,
            'pay_type' => $payType,
            'collection_days' => $collectionDays,
            'img_id' => $imgId,
            'img_url' => $imgUrl,
            'invoice_id' => $invoiceId,
            'invoice_name' => $invoiceName,
            'order_id' => $orderId,
            'customer_id' => $customerId,//新增，返回客户id
        ];

        return $re;
    }

    //创建订单第一步，提供默认值
    public function createCustomerOrderFirst()
    {
        $customerId = request('customer_id'); //客户id

        $customerObj = Customer::where(['id' => $customerId])->first();
        if ($customerObj) {
            $companyId = $customerObj->company_id;
            $companyName = Company::getOneValueById($companyId, 'title');
        } else {
            $companyId = '';//默认选择的工厂id
            $companyName = '';//默认选择的工厂名称
        }


        //判断是否是下单是否是客户本人
        $customerUserId = \App\Eloquent\Ygt\Customer::where(['id' => $customerId])->first()->user_id;
        $userId = Func::getHeaderValueByName('userid');
        $userInfo = DepartmentUser::getCurrentInfo($userId)->toArray();

        $ableChooseCompany = 0;
        if ($customerUserId == $userId) {
            $ableChooseCompany = 1;
        }


        $re = [
            'company_id' => $companyId,
            'company_name' => $companyName,
            'able_choose_company' => $ableChooseCompany,//能否选择工厂列表 1-允许选择 0-禁止选择
        ];

        return $re;
    }

    //管理员工单详情
    public function getManagerOrderDetailNew(Request $request)
    {
        //获取传入数据
        $input = $request->all();
        $input['order_id'] = isset($input['order_id']) ? $input['order_id'] : '';//工单-id


        //获取工单信息
        $orderInfo = Order::where('id', $input['order_id'])->first()->toArray();

        //处理图片数据
        $imgIdList = explode(',', $orderInfo['production_case_diagram']);
        $exampleImg = '';
        foreach ($imgIdList as $imgId) {
            if (!trim($imgId)) {//过滤空格 图片id应该不会有0
                continue;
            }
            if (!$exampleImg) {//取第一张图作为示例图
                $exampleImg = ImgUpload::getImgUrlById($imgId);
            }
        }

        //获取工单对应的所有工序
        $orderProcessList = OrderType::getAllOrderTypeProcess($orderInfo['order_type'])->toArray();
        $blueColor = '#00AAEE';
        $greColor = '#B5B5B5';
        $androidBgBlue = 'bluecircle.png';
        $androidBgGrey = 'graycircle.png';


        $list = [];//对应页面上横向列表
        $list[] = [
            'statusValue' => '',
            'departmentValue' => '待处理',
            'leftHiden' => 1,
            'rightHiden' => 0,
            'statusHiden' => 1,
            'departmentFontColor' => $blueColor,
            'statusViewBG' => $blueColor,
            'statusViewBorderColor' => $blueColor,
            'androidBg' => $androidBgBlue
        ];//默认自带条目

        $statusArray = [
            '1' => '待接单',
            '2' => '待分派',
            '3' => '生产中',
            '4' => '已完成',
            '101' => '待开工',
        ];

        $manageOrderProcessList = [];//工序工单信息
        foreach ($orderProcessList as $processId) {
            if (!$orderProcessInfo = OrderProcess::where(['order_id' => $orderInfo['id'], 'process_type' => $processId])->first()) {
                continue;
            }

            $orderProcessInfo = OrderProcess::where(['order_id' => $orderInfo['id'], 'process_type' => $processId])->first()->toArray();


            $processTitle = Process::getOneValueById($orderProcessInfo['process_type'], 'title');

            $preProcessEstimatedTime = $orderProcessInfo['start_time'] + $orderProcessInfo['estimated_time_hour'] * 3600 + $orderProcessInfo['estimated_time_minute'] * 60;


            //已完成状态可以查看
            $lookDetaileButtonHiden = 0;
            $buttontitle = '查看';
            $seeDetaileFunctionName = 'seeDetaileAction';

            ////判断下一个工序是否需要工序管理员分派
            ////如果该工序没有设置工序管理员&未分派
            $privilegeAssignmentIds = PermissionEngine::getStepActionPrivilegeIdsByOrderTypeProcess($orderInfo['order_type'], $processId, 3);//1:查看;2:可写;3:分配;4:提交;5:转发;
            if ($orderProcessInfo['uid']) {
                $userInfo = DepartmentUser::getCurrentInfo($orderProcessInfo['uid'])->toArray();
                $showUserName = $userInfo['truename'];
            } else {
                $showUserName = '';
            }

            if (!$privilegeAssignmentIds->count()) {//工序没有设置工序管理员
                //工单操作改为员工

                //没有配置工序管理员&员工还未分派工单
                $orderProcessCourse = OrderProcessCourse::where(['order_process_id' => $orderProcessInfo['id']])->get();
                if (!$orderProcessCourse->count()) {//表示未分派
                    $buttontitle = '分派';
                    $seeDetaileFunctionName = 'goSendAction';
                    $showUserName = '无';
                } else {
                    $userInfo = DepartmentUser::getCurrentInfo($orderProcessCourse->first()->uid)->toArray();
                    $showUserName = $userInfo['truename'];
                    if ($orderProcessCourse->count() > 1) {
                        $showUserName .= '等';
                    }
                }
            }

            if ($orderProcessInfo['status']) {//待接单状态不显示 调整--待接单状态也显示 20180305 18:30

                //调整-预计完成时间调整为从员工工单获取
                $orderProcessCourseList = OrderProcessCourse::where(['order_process_id' => $orderProcessInfo['id']])->get();
                $finishNum = 0;

                $processId = $orderProcessInfo['process_type'];
                $where = ['id' => $processId];
                $process = Process::withTrashed()->where($where)->first()->toArray();

                $processIsSum = $process['is_sum'];//工序数量是否累加0不累加1累加

                $finishUserNumList = [];
                $minStatrTime = 0;
                $maxEndTime = 0;
                foreach ($orderProcessCourseList as $orderProcessCourseRow) {

                    //设定的角色不进行统计数量到工序数量中
                    //过滤异常数据
                    if (!DepartmentUser::getCurrentInfo($orderProcessCourseRow['uid'])) {
                        continue;
                    }

                    if (!$minStatrTime || $orderProcessCourseRow['start_time'] < $minStatrTime) {
                        $minStatrTime = $orderProcessCourseRow['start_time'];
                    }

                    $tmpEndTime = $orderProcessCourseRow['start_time'] + (int)($orderProcessCourseRow['estimated_time_minute'] * 60);
                    if (!$maxEndTime || $tmpEndTime > $maxEndTime) {
                        $maxEndTime = $tmpEndTime;
                    }

                    $tmpUserInfo = DepartmentUser::getCurrentInfo($orderProcessCourseRow['uid'])->toArray();
                    $tmpPrivilegeId = $tmpUserInfo['privilege_id'];
                    if (OrderEngine::getProcessNumNoStatistics($tmpPrivilegeId)) {
                        continue;
                    }

                    $finishNum += $orderProcessCourseRow['finish_number'];
                    if (!$processIsSum) {//不累加
                        $tmpUserInfo = DepartmentUser::getCurrentInfo($orderProcessCourseRow['uid'])->toArray();
                        $tmpPrivilegeId = $tmpUserInfo['privilege_id'];

                        if (isset($finishUserNumList[$tmpPrivilegeId])) {
                            $finishUserNumList[$tmpPrivilegeId]['finish_number'] += $orderProcessCourseRow['finish_number'];
                        } else {
                            $finishUserNumList[$tmpPrivilegeId]['finish_number'] = $orderProcessCourseRow['finish_number'];
                        }
                    }
                }

                //不累加--未完工时取完成量最小的员工
                if (!empty($finishUserNumList)) {
                    $finishMinNum = '';
                    foreach ($finishUserNumList as $privilegeId => $finishUserNumRow) {
                        if ($finishMinNum === 0) {//如果有员工完成数量为0，
                            break;
                        }

                        if ($finishUserNumRow['finish_number'] < $finishMinNum || $finishMinNum === '') {//如果有员工完成数量更少，或者第一个员工的数据
                            $finishMinNum = $finishUserNumRow['finish_number'];
                        }
                    }
                    $finishNum = $finishMinNum;
                }

                //统计工序总共使用材料情况
                $orderProcessCourseList = OrderProcessCourse::where(['order_process_id' => $orderProcessInfo['id']])->get()->toArray();
                $orderPorcessCourseIds = [];
                $finishNum = 0;//已完成数量
                foreach ($orderProcessCourseList as $orderProcessCourseRow) {
                    $orderPorcessCourseIds[] = $orderProcessCourseRow['id'];
                    $finishNum += $orderProcessCourseRow['finish_number'];
                }

                $orderMaterialArr = OrderMaterialCourse::where(['process_type' => $orderProcessInfo['process_type']])->whereIn('order_process_course_id', $orderPorcessCourseIds)->orderBy('allow_delete','asc')->get()->toArray();

                $orderMaterialListTmp = [];
                foreach ($orderMaterialArr as $orderMaterialRow) {
                    if (isset($orderMaterialListTmp[$orderMaterialRow['material_id']])) {
                        $orderMaterialListTmp[$orderMaterialRow['material_id']]['receive_number'] += $orderMaterialRow['receive_number'];
                        $orderMaterialListTmp[$orderMaterialRow['material_id']]['residual_number'] += $orderMaterialRow['residual_number'];
                        $orderMaterialListTmp[$orderMaterialRow['material_id']]['scrap_number'] += $orderMaterialRow['scrap_number'];
                        $orderMaterialListTmp[$orderMaterialRow['material_id']]['retreat_number'] += $orderMaterialRow['retreat_number'];
                    } else {
                        $orderMaterialListTmp[$orderMaterialRow['material_id']] = $orderMaterialRow;
                    }
                }

                //兼容还没有领取材料的情况
                if(empty($orderMaterialListTmp)){
                    $tmpOrderMaterialList = \App\Eloquent\Ygt\OrderMaterial::where(['order_process_id' => $orderProcessInfo['id']])->get();
                    if ($tmpOrderMaterialList) {
                        foreach ($tmpOrderMaterialList as $tmpOrderMaterialRow){
                            $orderMaterialListTmp[$tmpOrderMaterialRow['material_id']] = [
                                'material_id' => $tmpOrderMaterialRow['material_id'],
                                'receive_number' => 0,
                                'residual_number' => 0,
                                'scrap_number' => 0,
                                'retreat_number' => 0,
                            ];
                        }
                    }
                }


                $orderMaterialList = [];
                foreach ($orderMaterialListTmp as $orderMaterialRow) {
//                    $materialRow = ProductEngine::getProductInfo($orderMaterialRow['material_id']);
//                    $materialRow = ProductEngine::getProductInfoExist($orderMaterialRow['material_id']);

                    //考虑集合材料的问题
                    if(strstr($orderMaterialRow['material_id'],'A')){
                        $tmpAssemblageMaterialId = str_replace('A','',$orderMaterialRow['material_id']);
                        $materialRow = \App\Eloquent\Ygt\AssemblageMaterial::where(['id'=>$tmpAssemblageMaterialId])->first();
                    }else{
                        $materialRow = ProductEngine::getProductInfoExist($orderMaterialRow['material_id']);
                    }

                    if (!$materialRow) {
                        //考虑集合材料的问题
                        if(strstr($orderMaterialRow['material_id'],'A')){
                            $tmpAssemblageMaterialId = str_replace('A','',$orderMaterialRow['material_id']);
                            $materialRow = \App\Eloquent\Ygt\AssemblageMaterial::withTrashed()->where(['id'=>$tmpAssemblageMaterialId])->first();
                        }else{
                            $materialRow = ProductEngine::getProductInfoTrash($orderMaterialRow['material_id']);
                        }

                        if(!$materialRow){
                            continue;
                        }

                        $materialRow['product_name'] = $materialRow['product_name'] . "[已删除]";
                    }



                    if ($materialRow['img_id']) {
                        $materialRow['img_url'] = ImgUpload::getImgUrlById($materialRow['img_id']);
                    }


                    //追加供应商 归属人
                    $materialRow['customer_name'] = '';
                    if($materialRow['customer_id']){
                        $materialRow['customer_name'] = \App\Eloquent\Ygt\Customer::getOneValueById($materialRow['customer_id'],'customer_name');
                    }

                    $materialRow['supplier_name'] = '';
                    if($materialRow['seller_company_id']){
                        $materialRow['supplier_name'] = \App\Eloquent\Ygt\SellerCompany::getOneValueById($materialRow['seller_company_id'],'title');
                    }

                    //追加材料自定义属性
                    $ProductFieldsModel = new \App\Eloquent\Ygt\ProductFields();

                    //调整完集合材料后
                    if(isset($materialRow['assemblage_material_id'])){
                        $tmpAssemblageMaterialId = $materialRow['assemblage_material_id'];
                    }else{
                        $tmpAssemblageMaterialId = $materialRow['id'];
                    }

                    $where = ['assemblage_material_id' => $tmpAssemblageMaterialId];
                    $productFields = \App\Eloquent\Ygt\ProductFields::where($where)->get();

                    $productFields = $productFields->map(function ($item) {
                        $data['field_name'] = $item->field_name;
                        $data['is_compute'] = $item->is_compute;
                        $comumnName = \App\Engine\Product::getFieldColumn($item->field_type);
                        $data['field_value'] = $item->$comumnName;
                        $data['unit'] = $item->unit;
                        return $data;
                    });

                    //过滤计量属性
                    $productFields = $productFields->toArray();
                    foreach ($productFields as $key => $row){
                        if($row['is_compute']){
                            unset($productFields[$key]);
                        }
                    }
                    $productFields = array_values($productFields);


                    $materialRow['custom_fields'] = $productFields;

                    $firstText      = $secondText = $thirdText = $customFieldsText = '';
                    $fieldsList         = $productFields;
                    if(!empty($fieldsList))
                    {
                        if(isset($fieldsList[0]))
                        {
                            $firstText   = $fieldsList[0]['field_name'].': '.$fieldsList[0]['field_value'].$fieldsList[0]['unit'];
                        }
                        if(isset($fieldsList[1]))
                        {
                            $secondText  = $fieldsList[1]['field_name'].': '.$fieldsList[1]['field_value'].$fieldsList[1]['unit'];
                        }
                        if(isset($fieldsList[2]))
                        {
                            $thirdText   = $fieldsList[2]['field_name'].': '.$fieldsList[2]['field_value'].$fieldsList[2]['unit'];
                        }
                    }

                    $customFieldsText                       = $firstText.' '.$secondText.' '.$thirdText;
                    $materialRow['first_text']           = $firstText;
                    $materialRow['second_text']          = $secondText;
                    $materialRow['third_text']           = $thirdText;
                    $materialRow['custom_fields_text']   = $customFieldsText;


                    $orderMaterialRow['info'] = $materialRow;
                    $orderMaterialList[] = $orderMaterialRow;
                }

                //统计工序开始时间&完工时间（预计） （开始时间取最早的员工开工时间，预计完工时间取最晚的完工时间）
                $orderProcessStartTime = $orderProcessEndTime = $orderProcessCostTime = '';
                $endTimeStr = "预计完成时间";
                if ($minStatrTime) {
                    $orderProcessStartTime = date('m-d H:i', $minStatrTime);
                }
                if ($maxEndTime) {
                    $orderProcessEndTime = date('m-d H:i', $maxEndTime);
                }

                if ($minStatrTime && $maxEndTime) {
                    $orderProcessCostTime = ((int)(($maxEndTime - $minStatrTime) / 3600 * 10)) / 10;//计算耗时，过滤浮点数很多小数位问题
                    $orderProcessCostTime .= '小时';
                }

                //工单完成后
                if($orderProcessInfo['status'] == 4){
                    $endTimeStr = "完成时间";
                    $orderProcessEndTime = date('m-d H:i', $orderProcessInfo['updated_at']);

                    $orderProcessCostTime = ((int)(($orderProcessInfo['updated_at'] - $minStatrTime) / 3600 * 10)) / 10;//计算耗时，过滤浮点数很多小数位问题
                    $orderProcessCostTime .= '小时';
                }


                //工序管理员名称
                $orderProcessManagerUid = $orderProcessInfo['uid'];
                $orderProcessManagerName = DepartmentUser::getCurrentInfo($orderProcessManagerUid)->truename;

                $manageOrderProcessList[] = [
                    'orderProcessId' => $orderProcessInfo['id'],//工序工单id
                    'orderProcessManagerName' => $orderProcessManagerName,//工序管理员名称
                    'processTitle' => $processTitle,//工序名称
                    'orderProcessStatus' => $statusArray[$orderProcessInfo['status']],//工序工单状态
                    'finishNum' => $finishNum,//工序完成数量（页面上没有，但我觉得肯定会用到，先预留着）
                    'orderMaterialList' => $orderMaterialList,//工序工单材料列表
                    'orderProcessStartTime' => $orderProcessStartTime,//工序开始时间
                    'orderProcessEndTime' => $orderProcessEndTime,//工序开始时间
                    'orderProcessCostTime' => $orderProcessCostTime,//工序耗时
                    'endTimeStr' => $endTimeStr,//工序耗时
                ];

            }


//            if($orderProcessInfo['status'] == 2 || $orderProcessInfo['status'] == 3){
            if (isset($orderProcessInfo['status']) && $orderProcessInfo['status'] && $orderProcessInfo['status'] != 1 && $orderProcessInfo['status'] != 101 && $orderProcessInfo['status'] != 2) {
                $statusValue = $statusArray[$orderProcessInfo['status']];
                $useColor = $blueColor;
                $androidBg = $androidBgBlue;
                $statusHiden = 0;
                $leftHiden = 0;
                $rightHiden = 0;
            } else {
                $statusValue = '';
                $useColor = $greColor;
                $androidBg = $androidBgGrey;
                $statusHiden = 1;
                $leftHiden = 0;
                $rightHiden = 0;
            }


            $list[] = [
                'statusValue' => $statusValue,//'生产中'
                'departmentValue' => $processTitle,//'彩印部门'
                'leftHiden' => $leftHiden,
                'rightHiden' => $rightHiden,
                'statusHiden' => $statusHiden,
                'departmentFontColor' => $useColor,
                'statusViewBG' => $useColor,
                'statusViewBorderColor' => $useColor,
                'androidBg' => $androidBg
            ];
        }

        if ($orderInfo['status'] == 3) {//已经完成
            $statusValue = '已完成';
            $processTitle = '已完成';
            $useColor = $blueColor;
            $androidBg = $androidBgBlue;
            $statusHiden = 0;
            $leftHiden = 0;
            $rightHiden = 1;
        } else {
            $statusValue = '';
            $processTitle = '已完成';
            $useColor = $greColor;
            $androidBg = $androidBgGrey;
            $statusHiden = 1;
            $leftHiden = 0;
            $rightHiden = 1;
        }
        $list[] = [
            'statusValue' => $statusValue,//'生产中'
            'departmentValue' => $processTitle,//'彩印部门'
            'leftHiden' => $leftHiden,
            'rightHiden' => $rightHiden,
            'statusHiden' => $statusHiden,
            'departmentFontColor' => $useColor,
            'statusViewBG' => $useColor,
            'statusViewBorderColor' => $useColor,
            'androidBg' => $androidBg
        ];

        //获取工序对应的详细信息
        //获取工序类型名称
        $orderTypeTitle = OrderType::getOneValueById($orderInfo['order_type'], 'title');

        $returnApe = [
            'productImage' => $exampleImg,
            'productNameValue' => $orderTypeTitle,
            'productOrderValue' => '生产单号:' . $orderInfo['order_title'],
            'orderId' => $orderInfo['id'],
            'list' => $list,
            'manageOrderProcessList' => $manageOrderProcessList,
        ];
        return $returnApe;
    }

    public function getProcessManagerOrderDetailNew()
    {
        $orderProcessId = request('order_process_id');
        $order_process_info = OrderProcess::where('id', $orderProcessId)->first();

        $processTitle = Process::getOneValueById($order_process_info['process_type'], 'title');

        //工艺单位
        $curProcessMeasurementUnit = Process::getOneValueById($order_process_info['process_type'], 'measurement_unit');
        if(!$curProcessMeasurementUnit){
            $curProcessMeasurementUnit = '';
        }


        $statusArray = [
            '1' => '待接单',
            '2' => '待分派',
            '3' => '生产中',
            '4' => '已完成',
            '101' => '待开工',
        ];
        $processStatusStr = $statusArray[$order_process_info['status']];
        $processInfoStr = $processStatusStr . '[' . $processTitle . ']';

        $orderinfo = $this->info($order_process_info->order_id);

        ////替换产品名称为工序类型名称
        //获取工序类型名称
        $orderTypeTitle = OrderType::getOneValueById($orderinfo['order_type'], 'title');
        $orderinfo['product_name'] = $orderTypeTitle;

        $list = OrderProcessCourse::getAllWithUser($orderProcessId, $order_process_info['company_id']);

        //增加限制-是否允许重新派单
        $userId = Func::getHeaderValueByName('userid');
        foreach ($list as &$row) {
            $row['is_allow_write'] = 0;
            if ($userId == $order_process_info['uid']) {//允许
                $row['is_allow_write'] = 1;
            }
        }


        $courseStatusArray = [
            '1' => '待开工',
            '2' => '待领取材料',
            '3' => '生产中',
            '4' => '已完成',
        ];
        $list->transform(function ($item) use ($courseStatusArray) {
            $item->statusStr = $courseStatusArray[$item->status];
            $item->creat_time = $item->created_at->formatLocalized('%Y-%m-%d');
            if (!$item->waste_number) {
                $item->waste_number = 0;
            }
            return $item;
        });


        //统计工序完成数量
        $processIsSum = Process::getOneValueById($order_process_info['process_type'], 'is_sum');

        $tmpUserList = [];
        $finishUserNumList = [];
        //员工分组，按角色分类
        $allMoney = 0;//总计件工资
        $finishNum = 0;//总完成数量
        $privilegeWageList = [];
        foreach ($list as $tmpRow) {
            $tmpUid = $tmpRow->uid;

            //获取用户id对应角色id
            $tmpUserInfo = DepartmentUser::getCurrentInfo($tmpUid)->toArray();
            $tmpPrivilegeId = $tmpUserInfo['privilege_id'];
            $tmpPrivilegeTitle = Privilege::getOneValueById($tmpPrivilegeId, 'title');


            ////计价工资调整为管理员在工单里设置的值
            //先判断有没有批量设置角色计件工资
            $tmpOrderWage = '';
            $tmpOrderProcessId = $tmpRow['order_process_id'];
            $tmpOrderWageObj = \App\Eloquent\Ygt\OrderWage::where(['order_process_id' => $tmpOrderProcessId, 'privilege_id' => $tmpPrivilegeId])->first();
            if ($tmpOrderWageObj) {
                $tmpOrderWage = $tmpOrderWageObj->piece_wage;
                if (!isset($privilegeWageList[$tmpPrivilegeId])) {
                    $privilegeWageList[$tmpPrivilegeId] = $tmpOrderWage;
                }
            }

            //设置在个人上的计件工资优先级更高
            $tmpOrderWageObj = \App\Eloquent\Ygt\OrderWage::where(['order_process_course_id' => $tmpRow['id']])->first();
            if ($tmpOrderWageObj) {
                $tmpOrderWage = $tmpOrderWageObj->piece_wage;
            }

            $tmpRow->price = $tmpOrderWage;
            $tmpRow->money = $tmpUserInfo['price'] * $tmpRow['finish_number'];

            //增加开工，完工（预计）时间，耗时
            $startTime = $endTimeStamp = $endTime = $costTime = '';
            $endTimeStr = "预计完工时间";
            if ($tmpRow->start_time) {
                $startTime = date('m-d H:i', $tmpRow->start_time);
            }

            //用时调整为实际完成时间-开工时间 zhuyujun 20181126
            //最近操作日期
            $tmpRowArr = $tmpRow->toArray();
            $tmpRow->workDate = date('m-d H:i', $tmpRowArr['updated_at']);
            //如果提交数量为0 不展示提交时间
            $tmpRow->submitLog = [];
            if(!$tmpRow['finish_number']){
                $tmpRow->workDate = '---';
            }else{
                //获取分批提交记录
                //分批提交数量展示
                $where = [
                    ['order_process_course_id', '=', $tmpRow['id']],
                    ['submit_num', '>', 0],
                ];
                $orderProcessCourseGradationList = \App\Eloquent\Ygt\OrderProcessCourseGradation::where($where)->get();
                $submitList = [];
                foreach ($orderProcessCourseGradationList as $orderProcessCourseGradationRow) {
                    $tmpArr = [
                        'id' => $orderProcessCourseGradationRow['id'],
                        'submit_date' => date('Y.m.d', $orderProcessCourseGradationRow['submit_time']),
                        'submit_num' => $orderProcessCourseGradationRow['submit_num']
                    ];
                    $submitList[] = $tmpArr;
                }

                $tmpRow->submitLog = $submitList;

            }


            //进行中 -- 显示预计完工时间
            if($tmpRow->status == 3){
                $endTimeStamp = $tmpRow->start_time + (int)($tmpRow->estimated_time_minute * 60);
                $endTime = date('m-d H:i', $endTimeStamp);
                $costTime = ((int)(($endTimeStamp - $tmpRow->start_time) / 3600 * 10)) / 10;//计算耗时，过滤浮点数很多小数位问题
                $costTime .= '小时';
            }

            //完工时 --显示实际完工时间
            if($tmpRow->status == 4){
                $endTimeStr = "完工时间";
                $endTimeStamp = $tmpRow->start_time + (int)($tmpRow->estimated_time_minute * 60);
                $endTime = date('m-d H:i', $tmpRowArr['updated_at']);
                $costTime = ((int)(($tmpRowArr['updated_at'] - $tmpRow->start_time) / 3600 * 10)) / 10;//计算耗时，过滤浮点数很多小数位问题
                $costTime .= '小时';
            }

            $tmpRow->startTime = $startTime;
            $tmpRow->endTime = $endTime;
            $tmpRow->costTime = $costTime;
            $tmpRow->endTimeStr = $endTimeStr;

            if (isset($tmpUserList[$tmpPrivilegeId])) {
                $tmpUserList[$tmpPrivilegeId]['sumNumber'] += $tmpRow->finish_number;//同角色总数量
                $tmpUserList[$tmpPrivilegeId]['sumMoney'] += $tmpRow->finish_number * $tmpRow->price;//同角色总计件工资
                $tmpUserList[$tmpPrivilegeId]['sumUserNum']++;//同角色总人数

                $tmpUserList[$tmpPrivilegeId]['userList'][] = $tmpRow;
                $allMoney += $tmpRow->finish_number * $tmpRow->price;
            } else {
                $tmpUserList[$tmpPrivilegeId]['privilegeId'] = $tmpPrivilegeId;
                $tmpUserList[$tmpPrivilegeId]['privilegeTitle'] = $tmpPrivilegeTitle;
                $tmpUserList[$tmpPrivilegeId]['sumNumber'] = $tmpRow->finish_number;
                $tmpUserList[$tmpPrivilegeId]['sumMoney'] = $tmpRow->finish_number * $tmpRow->price;
                $tmpUserList[$tmpPrivilegeId]['sumUserNum'] = 1;
                $tmpPrivilegePieceWage = isset($privilegeWageList[$tmpPrivilegeId]) ? $privilegeWageList[$tmpPrivilegeId] : '';

                $tmpUserList[$tmpPrivilegeId]['privilege_piece_wage'] = $tmpPrivilegePieceWage;

                $tmpUserList[$tmpPrivilegeId]['userList'][] = $tmpRow;
                $allMoney += $tmpRow->finish_number * $tmpRow->price;
            }


            //设定的角色不进行统计数量到工序数量中
            //过滤异常数据
            if (!DepartmentUser::getCurrentInfo($tmpRow->uid)) {
                continue;
            }
            $tmpUserInfo = DepartmentUser::getCurrentInfo($tmpRow->uid)->toArray();
            $tmpPrivilegeId = $tmpUserInfo['privilege_id'];
            if (OrderEngine::getProcessNumNoStatistics($tmpPrivilegeId)) {
                continue;
            }


            $finishNum += $tmpRow->finish_number;

            if (!$processIsSum) {//不累加
                if (isset($finishUserNumList[$tmpPrivilegeId])) {
                    $finishUserNumList[$tmpPrivilegeId]['finish_number'] += $tmpRow['finish_number'];
                } else {
                    $finishUserNumList[$tmpPrivilegeId]['finish_number'] = $tmpRow['finish_number'];
                }
            }
        }


        //不累加--未完工时取完成量最小的员工
        if (!empty($finishUserNumList)) {
            $finishMinNum = '';
            foreach ($finishUserNumList as $finishUserNumRow) {
                if ($finishMinNum === 0) {//如果有员工完成数量为0，
                    break;
                }

                if ($finishUserNumRow['finish_number'] < $finishMinNum || $finishMinNum === '') {//如果有员工完成数量更少，或者第一个员工的数据
                    $finishMinNum = $finishUserNumRow['finish_number'];
                }
            }
            $finishNum = $finishMinNum;
        }

        //统计工序总共使用材料情况 || 调整 按角色区分
        $orderProcessInfo = $order_process_info;//变量保持一致
        $orderProcessCourseList = OrderProcessCourse::where(['order_process_id' => $orderProcessInfo['id']])->get()->toArray();
        $orderPorcessCourseIds = [];
        $orderMaterialListTmp = [];
        foreach ($orderProcessCourseList as $orderProcessCourseRow) {
            $tmpUid = $orderProcessCourseRow['uid'];
            //获取用户id对应角色id
            $tmpUserInfo = DepartmentUser::getCurrentInfo($tmpUid)->toArray();
            $tmpPrivilegeId = $tmpUserInfo['privilege_id'];
            $tmpPrivilegeTitle = Privilege::getOneValueById($tmpPrivilegeId, 'title');

            $orderMaterialArr = OrderMaterialCourse::where(['process_type' => $orderProcessInfo['process_type'], 'order_process_course_id' => $orderProcessCourseRow['id']])->orderBy('allow_delete','asc')->get()->toArray();

            foreach ($orderMaterialArr as $orderMaterialRow) {

                //调整为整个工序的材料而不是通过角色区分 20180707 朱雨骏
                if (isset($orderMaterialListTmp[$orderMaterialRow['material_id']])) {
                    $orderMaterialListTmp[$orderMaterialRow['material_id']]['receive_number'] += $orderMaterialRow['receive_number'];
                    $orderMaterialListTmp[$orderMaterialRow['material_id']]['residual_number'] += $orderMaterialRow['residual_number'];
                    $orderMaterialListTmp[$orderMaterialRow['material_id']]['scrap_number'] += $orderMaterialRow['scrap_number'];
                    $orderMaterialListTmp[$orderMaterialRow['material_id']]['retreat_number'] += $orderMaterialRow['retreat_number'];

                } else {
                    $orderMaterialListTmp[$orderMaterialRow['material_id']] = $orderMaterialRow;
                }
            }
        }


        //兼容还没有领取材料的情况
        if(empty($orderMaterialListTmp)){
            $tmpOrderMaterialList = \App\Eloquent\Ygt\OrderMaterial::where(['order_process_id' => $orderProcessInfo['id']])->get();
            if ($tmpOrderMaterialList) {
                foreach ($tmpOrderMaterialList as $tmpOrderMaterialRow){
                    $orderMaterialListTmp[$tmpOrderMaterialRow['material_id']] = [
                        'material_id' => $tmpOrderMaterialRow['material_id'],
                        'receive_number' => 0,
                        'residual_number' => 0,
                        'scrap_number' => 0,
                        'retreat_number' => 0,
                    ];
                }
            }
        }


        $orderMaterialList = [];
//        foreach ($orderMaterialListTmp as $tmpPrivilegeId => $orderMaterialListTmp) {
        foreach ($orderMaterialListTmp as $orderMaterialRow) {
//                $materialRow = ProductEngine::getProductInfo($orderMaterialRow['material_id']);
//            $materialRow = ProductEngine::getProductInfoExist($orderMaterialRow['material_id']);

            //考虑集合材料的问题
            if(strstr($orderMaterialRow['material_id'],'A')){
                $tmpAssemblageMaterialId = str_replace('A','',$orderMaterialRow['material_id']);
                $materialRow = \App\Eloquent\Ygt\AssemblageMaterial::where(['id'=>$tmpAssemblageMaterialId])->first();
            }else{
                $materialRow = ProductEngine::getProductInfoExist($orderMaterialRow['material_id']);
            }

            if (!$materialRow) {
                //考虑集合材料的问题
                if(strstr($orderMaterialRow['material_id'],'A')){
                    $tmpAssemblageMaterialId = str_replace('A','',$orderMaterialRow['material_id']);
                    $materialRow = \App\Eloquent\Ygt\AssemblageMaterial::withTrashed()->where(['id'=>$tmpAssemblageMaterialId])->first();
                }else{
                    $materialRow = ProductEngine::getProductInfoTrash($orderMaterialRow['material_id']);
                }
                if(!$materialRow){
                    continue;
                }

                $materialRow['product_name'] = $materialRow['product_name'] . "[已删除]";
            }

            //补齐 供应商 归属人 属性
            if($materialRow['customer_id']){
                $materialRow['customer_name']= \App\Eloquent\Ygt\Customer::getOneValueById($materialRow['customer_id'],'customer_name');
            }

            if($materialRow['seller_company_id']){
                $materialRow['supplier_name']= \App\Eloquent\Ygt\SellerCompany::getOneValueById($materialRow['seller_company_id'],'title');
            }


            //追加材料图片地址
            $materialRow['img_url'] = '';
            if ($materialRow['img_id']) {
                $materialRow['img_url'] = ImgUpload::getImgUrlById($materialRow['img_id']);
            }

            //追加材料自定义属性
            $ProductFieldsModel = new \App\Eloquent\Ygt\ProductFields();

            //调整完集合材料后
            if(isset($materialRow['assemblage_material_id'])){
                $tmpAssemblageMaterialId = $materialRow['assemblage_material_id'];
            }else{
                $tmpAssemblageMaterialId = $materialRow['id'];
            }

            $where = ['assemblage_material_id' => $tmpAssemblageMaterialId];
            $productFields = \App\Eloquent\Ygt\ProductFields::where($where)->get();

            $productFields = $productFields->map(function ($item) {
                $data['field_name'] = $item->field_name;
                $data['is_compute'] = $item->is_compute;
                $comumnName = \App\Engine\Product::getFieldColumn($item->field_type);
                $data['field_value'] = $item->$comumnName;
                $data['unit'] = $item->unit;
                return $data;
            });

            //过滤计量属性
            $productFields = $productFields->toArray();
            foreach ($productFields as $key => $row){
                if($row['is_compute']){
                    unset($productFields[$key]);
                }
            }
            $productFields = array_values($productFields);

            $materialRow['custom_fields'] = $productFields;
            $firstText      = $secondText = $thirdText = $customFieldsText = '';
            $fieldsList         = $productFields;

            if(!empty($fieldsList))
            {
                if(isset($fieldsList[0]))
                {
                    $firstText   = $fieldsList[0]['field_name'].': '.$fieldsList[0]['field_value'].$fieldsList[0]['unit'];
                }
                if(isset($fieldsList[1]))
                {
                    $secondText  = $fieldsList[1]['field_name'].': '.$fieldsList[1]['field_value'].$fieldsList[1]['unit'];
                }
                if(isset($fieldsList[2]))
                {
                    $thirdText   = $fieldsList[2]['field_name'].': '.$fieldsList[2]['field_value'].$fieldsList[2]['unit'];
                }
            }

            $customFieldsText                       = $firstText.' '.$secondText.' '.$thirdText;
            $materialRow['first_text']           = $firstText;
            $materialRow['second_text']          = $secondText;
            $materialRow['third_text']           = $thirdText;
            $materialRow['custom_fields_text']   = $customFieldsText;


            $orderMaterialRow['info'] = $materialRow;
            $orderMaterialList[] = $orderMaterialRow;
        }
//        }

//        foreach ($orderMaterialList as $tmpPrivilegeId => $tmpOrderMaterialList) {
//            $tmpUserList[$tmpPrivilegeId]['orderMaterialList'] = $tmpOrderMaterialList;
//        }
        //角色列表排序

        $where = [];
        $where['ordertype_process_id'] = $order_process_info['ordertype_process_id'];
        $where['action_type'] = 4;

        $ordertypeProcessPrivilegeList = \App\Eloquent\Ygt\OrdertypeProcessPrivilegeSort::where($where)->orderBy('sort', 'desc')->get();

        $tmpArr = [];//保存排序后角色列表信息
        foreach ($ordertypeProcessPrivilegeList as $ordertypeProcessPrivilegeRow) {
            if (isset($tmpUserList[$ordertypeProcessPrivilegeRow['privilege_id']])) {
                $tmpArr[$ordertypeProcessPrivilegeRow['privilege_id']] = $tmpUserList[$ordertypeProcessPrivilegeRow['privilege_id']];
                unset($tmpUserList[$ordertypeProcessPrivilegeRow['privilege_id']]);
            }
        }

        //是否显示金额相关的数据 true-隐藏  false-显示
        $isHideMoneyData = OrderEngine::getHideMoneyDataByProcessId($order_process_info['process_type']);

        foreach ($tmpUserList as $tmpPrivilegeId => $tmpRow) {
            $tmpArr[$tmpPrivilegeId] = $tmpRow;
            $tmpArr[$tmpPrivilegeId]['isHideMoneyData'] = $isHideMoneyData;
        }

        $list = array_values($tmpArr);

        $isAllowReset = 1;//是否允许重新派单 1-允许 2-不允许
        //如果工单已经开工，不允许再开工
        if ($order_process_info['status'] == 3 || $order_process_info['status'] == 4) {
            $isAllowReset = 2;
        }

        //如果工序管理员不允许重新分派工单
//        if ($userId != $order_process_info['uid'] && $userId != $orderinfo['uid']) {
        if ($userId != $order_process_info['uid']) {
            $isAllowReset = 2;
        }


        //获取上一个部门
        $orderInfo = $orderinfo;//变量统一
        $preProcessList = OrderType::getAllPrevOrderProcess($orderInfo['order_type'], $orderProcessInfo['process_type'])->toArray();
        //获取预估完成时间最晚的一个，待开工的部门优先级最高
        $preProcess = '';//上一个工序（部门）
        $preProcessEstimatedTime = 0;
        $preProcessEstimatedTimeStr = '';
        $lastOrderProcessId = 0;
        $preFinishNum = 0;
        $processMeasurementUnit = '';
        $isPreEmpty = 0;

        if ($preProcessList) {
            foreach ($preProcessList as $processId) {
                //获取工序信息
                $orderProcessInfo = OrderProcess::where(['order_id' => $orderInfo['id'], 'process_type' => $processId])->first()->toArray();
                $lastOrderProcessId = $orderProcessInfo['id'];

                //获取工序数量是否需要叠加&工序名称
                $where = ['id' => $processId];
                $process = Process::getInfo($where)->toArray();
                $preProcess = $process['title'];//工序名称
                $processIsSum = $process['is_sum'];//工序数量是否累加 0-不累加 1-累加

                if ($orderProcessInfo['status'] == 1) {//待开工
                    $preProcessEstimatedTimeStr = '待开工';
                    break;
                } else {

                    //调整-预计完成时间调整为从员工工单获取
                    $orderProcessCourseList = OrderProcessCourse::where(['order_process_id' => $orderProcessInfo['id']])->get();
                    $preFinishNum = 0;

                    $finishUserNumList = [];
                    foreach ($orderProcessCourseList as $orderProcessCourseRow) {


                        $tmpPreProcessEstimatedTime = $orderProcessCourseRow['start_time'] + $orderProcessCourseRow['estimated_time_hour'] * 3600 + $orderProcessCourseRow['estimated_time_minute'] * 60;
                        if ($tmpPreProcessEstimatedTime > $preProcessEstimatedTime) {
                            $preProcessEstimatedTime = $tmpPreProcessEstimatedTime;
                            $preProcessEstimatedTimeStr = date('Y年m月d日H时', $preProcessEstimatedTime);
                        }

                        //设定的角色不进行统计数量到工序数量中
                        //过滤异常数据
                        if (!DepartmentUser::getCurrentInfo($orderProcessCourseRow['uid'])) {
                            continue;
                        }
                        $tmpUserInfo = DepartmentUser::getCurrentInfo($orderProcessCourseRow['uid'])->toArray();
                        $tmpPrivilegeId = $tmpUserInfo['privilege_id'];
                        if (OrderEngine::getProcessNumNoStatistics($tmpPrivilegeId)) {
                            continue;
                        }

                        $preFinishNum += $orderProcessCourseRow['finish_number'];
                        if (!$processIsSum) {//不累加
                            $tmpUserInfo = DepartmentUser::getCurrentInfo($orderProcessCourseRow['uid'])->toArray();
                            $tmpPrivilegeId = $tmpUserInfo['privilege_id'];
                            if (isset($finishUserNumList[$tmpPrivilegeId])) {
                                $finishUserNumList[$tmpPrivilegeId]['finish_number'] += $orderProcessCourseRow['finish_number'];
                            } else {
                                $finishUserNumList[$tmpPrivilegeId]['finish_number'] = $orderProcessCourseRow['finish_number'];
                            }
                        }
                    }


                    if ($preProcessEstimatedTime < 631152000) {//过滤1970的情况
                        $preProcessEstimatedTimeStr = '';
                    }

                    //不累加--未完工时取完成量最小的员工
                    if (!empty($finishUserNumList)) {
                        $finishMinNum = '';
                        foreach ($finishUserNumList as $finishUserNumRow) {
                            if ($finishMinNum === 0) {//如果有员工完成数量为0，
                                break;
                            }

                            if ($finishUserNumRow['finish_number'] < $finishMinNum || $finishMinNum === '') {//如果有员工完成数量更少，或者第一个员工的数据
                                $finishMinNum = $finishUserNumRow['finish_number'];
                            }
                        }
                        $preFinishNum = $finishMinNum;
                        $processMeasurementUnit = $process['measurement_unit'];
                    }

                }
            }
        } else {
            $preProcess = '无';//上一个工序（部门）
            $preProcessEstimatedTimeStr = '';
            $isPreEmpty = 1;
        }

        $preProcessInfo = [
            'preProcess' => $preProcess,
            'preProcessEstimatedTime' => $preProcessEstimatedTime,
            'preProcessEstimatedTimeStr' => $preProcessEstimatedTimeStr,
            'lastOrderProcessId' => $lastOrderProcessId,
            'finishNum' => $preFinishNum.$processMeasurementUnit,
            'is_pre_empty' => $isPreEmpty,
        ];


        ////控制领料按钮和提交用料按钮
        $buttonList = [];
        //工单完工后不能领取材料，否则允许领取材料

        if($order_process_info['status'] == 4){
            $buttonList[] = [
                'title' => '提交用料情况',
                'type' => 'submit_material',
            ];
        }else{
            $buttonList[] = [
                'title' => '领取材料',
                'type' => 'receive_material',
            ];
            $buttonList[] = [
                'title' => '提交用料情况',
                'type' => 'submit_material',
            ];
        }

        ////如果不是指派的工序管理员
        //不能领取提交材料
        if($order_process_info['uid'] != $userId){
            $buttonList  = [];
        }

        //工序完成数量加上单位
        $finishNum = $finishNum.$curProcessMeasurementUnit;
        foreach ($list as $k => $v){
            $list[$k]['sumNumber'] .= $curProcessMeasurementUnit;
            foreach ($v['userList'] as $kk => $vv ){
                $list[$k]['userList'][$kk]['finish_number'] .= $curProcessMeasurementUnit;
            }
        }



        return compact('processInfoStr', 'isAllowReset', 'orderProcessId', 'finishNum', 'allMoney', 'orderinfo', 'list', 'isHideMoneyData', 'preProcessInfo', 'orderMaterialList','buttonList');
    }

    //获取未议定价格订单列表
    public function getCustomerOrderNoDealPriceList()
    {
        $userId = Func::getHeaderValueByName('userid');
        $userInfo = DepartmentUser::getCurrentInfo($userId)->toArray();
        $companyId = $userInfo['company_id'];

        $customerOrderList = \App\Eloquent\Ygt\CustomerOrder::where(['company_id' => $companyId, 'is_deal_price' => 0])->orderBy('id', 'desc')->get()->toArray();

        //客户的另外处理
        if ($companyId == 2) {
            $customerOrderIdList = \App\Eloquent\Ygt\CustomerOrderPrice::where(['customer_uid' => $userId])->get()->pluck('customer_order_id');
            $customerOrderList = \App\Eloquent\Ygt\CustomerOrder::whereIn('id', $customerOrderIdList)->orderBy('id', 'desc')->get()->toArray();
        } else {
            $customerOrderIdList = \App\Eloquent\Ygt\CustomerOrderPrice::where(['company_id' => $companyId])->get()->pluck('customer_order_id');
            $customerOrderList = \App\Eloquent\Ygt\CustomerOrder::whereIn('id', $customerOrderIdList)->orderBy('id', 'desc')->get()->toArray();
        }


        $tmpOrderList = [];
        foreach ($customerOrderList as $tmpCustomerOrderRow) {
            if (isset($tmpCustomerOrderRow['product_num'])) {
                $tmpArr = explode(',', $tmpCustomerOrderRow['product_num']);
                $tmpCustomerOrderRow['product_num'] = '';
                foreach ($tmpArr as $tmpValue) {
                    $tmpCustomerOrderRow['product_num'] .= $tmpValue;
                }
            }

            //成品规格数据处理
            if (isset($tmpCustomerOrderRow['finished_specification'])) {
                $tmpArr = explode(',', $tmpCustomerOrderRow['finished_specification']);
                if (count($tmpArr) == 2) {
                    $tmpCustomerOrderRow['finished_specification'] = sprintf("%s×%s厘米", $tmpArr[0], $tmpArr[1]);
                }

                if (count($tmpArr) == 3) {
                    $tmpCustomerOrderRow['finished_specification'] = sprintf("%s×%s×%s厘米", $tmpArr[0], $tmpArr[1], $tmpArr[2]);
                }

                //如果数据都为空，显示为空
                $hasData = false;
                foreach ($tmpArr as $tmpValue) {
                    if ($tmpValue) {
                        $hasData = true;
                    }
                }

                if (!$hasData) {
                    $tmpCustomerOrderRow['finished_specification'] = '';
                }
            }

            //单位名称显示处理
            if (isset($tmpCustomerOrderRow['field_name_23'])) {
                $baseId = $tmpCustomerOrderRow['field_name_23'];
                $showTitle = Buyers::getNameById($tmpCustomerOrderRow['field_name_23']);
                if (!$showTitle) {
                    $showTitle = $tmpCustomerOrderRow['field_name_23'];
                }
                $tmpCustomerOrderRow['field_name_23'] = $showTitle;
            }

            //获取生产实例图
            $productionCaseDiagramIds = isset($tmpCustomerOrderRow['production_case_diagram']) ? $tmpCustomerOrderRow['production_case_diagram'] : '';
            if ($productionCaseDiagramIds) {
                $tmpArr = explode(',', $productionCaseDiagramIds);
                $productionCaseDiagramId = reset($tmpArr);
                $productionCaseDiagram = ImgUpload::getImgUrlById($productionCaseDiagramId);
                if (!$productionCaseDiagram) {//未获取到id对应的图片
                    $productionCaseDiagram = env('APP_URL') . '/assets/mobile/common/images/order_list_default.png';
                }

            } else {
                $productionCaseDiagram = env('APP_URL') . '/assets/mobile/common/images/order_list_default.png';
            }

            //订单创建时间（派发时间）
            $orderCreateTime = $tmpCustomerOrderRow['created_at'];
            if ($orderCreateTime) {
                $orderCreateTime = date('Y-m-d', $orderCreateTime);
                if ($orderCreateTime < 631152000) {//过滤1970的情况
                    $orderCreateTime = '';
                }
            } else {
                $orderCreateTime = '';
            }

            //获取工序类型名称
            $orderTypeTitle = OrderType::getOneValueById($tmpCustomerOrderRow['order_type'], 'title');


            $statusColor = 'FE7E57';//默认颜色
            //获取订单价格商议状态
            $customerOrderPriceStatus = \App\Eloquent\Ygt\CustomerOrderPrice::where(['customer_order_id' => $tmpCustomerOrderRow['id']])->first()->status;
            $customerOrderPriceStatusArr = config('order.customer_order_price_status_list');
            if (isset($customerOrderPriceStatusArr[$customerOrderPriceStatus])) {
                $customerOrderStatusStr = $customerOrderPriceStatusArr[$customerOrderPriceStatus]['txt'];
                $statusColor = $customerOrderPriceStatusArr[$customerOrderPriceStatus]['color'];
            } else {
                $customerOrderStatusStr = '';
            }

            $productName = \App\Engine\OrderEngine::getOrderFiledValueTrue($tmpCustomerOrderRow['product_name'], 20);
            $tmpOrderList[] = [
                'ordertype_title' => '工艺:',//工单列表展示字段
                'order_title' => '单号:',//工单列表展示字段
                'unit_name' => isset($tmpCustomerOrderRow['field_name_23']) ? $tmpCustomerOrderRow['field_name_23'] : '',//新加字段单位
                'product_name' => isset($productName) ? $productName : '',//新加字段品名
                'order_title_value' => $tmpCustomerOrderRow['order_title'],//新加字段单号
                'firstPropertyName' => '成品规格',
                'secondPropertyName' => '数量',
                'thirdPropertyName' => '交货日期',
                'thirdPropertyValue' => $tmpCustomerOrderRow['finished_date'],
                'secondPropertyValue' => $tmpCustomerOrderRow['product_num'],
                'firstPropertyValue' => isset($tmpCustomerOrderRow['finished_specification']) ? $tmpCustomerOrderRow['finished_specification'] : '',
                'productionCaseDiagram' => $productionCaseDiagram,
                'productOrderTimeValue' => $orderCreateTime,
                'orderTypeTitle' => $orderTypeTitle,
                'relate_id' => $tmpCustomerOrderRow['id'],
                'orderStatus' => $customerOrderStatusStr,
                'statusColor' => $statusColor,
            ];
        }

        $orderList = $tmpOrderList;

        $re['pageID'] = 0;
        $re['data']['tableviewSource'] = $orderList;

        return $re;

        return $customerOrderList;
    }

    //获取未议定价格订单详情
    public function getCustomerOrderNoDealPriceDetail()
    {
        $userId = Func::getHeaderValueByName('userid',25);
        $userInfo = DepartmentUser::getCurrentInfo($userId)->toArray();

        $customerOrderId = request('customer_order_id');
        $customerOrderRow = \App\Eloquent\Ygt\CustomerOrder::where(['id' => $customerOrderId])->first()->toArray();
        $customerOrderPriceRow = \App\Eloquent\Ygt\CustomerOrderPrice::where(['customer_order_id' => $customerOrderId])->first();
        $companyId = $customerOrderRow['company_id'];


        //获取客户ID对应的用户ID
        $customerId = $customerOrderRow['customer_name'];
        $tmpObj = \App\Eloquent\Ygt\Customer::where(['id' => $customerId])->first();
        $customerUserId = '';
        if ($tmpObj) {
            $customerUserId = $tmpObj->user_id;
        }


        ////通过订单ID，用户ID，状态显示不同的按钮
        //transferToSingleperson -- 转交给下单人
        //singlepersonSubmitPrices -- 下单人提交价格
        //transferToCustomer -- 转交给客户
        //customerSubmit -- 客户提交
        //sellerSubmit -- 销售员提交

        $showPriceFiled = 0;//是否显示订单价格按钮 0-隐藏 1-显示
        $editCustomerOrder = 0;//是否可以修改订单字段 0-禁止 1-允许
        $submitButtonList = [];//页面上展示的按钮
        $showChagedData = 1;//展示订单信息中修改过的字段
        $topTips = null;//顶部显示的文字（包括颜色）
        $customerOrderPirceArr = null;//订单价格相关配置
        $otherOrderPriceList = [];//其他价格相关配置

        //$customerOrderPriceRow = \App\Eloquent\Ygt\CustomerOrderPrice::where(['customer_order_id' => $customerOrderId])->first();
        $editionFeeTypeList = config('order.customer_order_edition_fee_type_list');
        $dealEditionFeeTypeList = [];
        foreach ($editionFeeTypeList as $id => $value) {
            $dealEditionFeeTypeList[] = [
                'id' => $id,
                'title' => $value
            ];
        }

        if ($customerOrderPriceRow) {
            switch ($customerOrderPriceRow['status']) {
                case '1':
                    ////销售员转交给下单人阶段
                    //判断用户是否为销售员
                    $privilegeIdList = \App\Engine\OrderEngine::getPrivilegeByNode($companyId, 13);
                    if (in_array($userInfo['privilege_id'], $privilegeIdList)) {
                        //如果用户同时为下单人，直接到下单人填写价格流程
                        $privilegeIdList2 = \App\Engine\OrderEngine::getPrivilegeByNode($companyId, 1);
//                        if (in_array($userInfo['privilege_id'], $privilegeIdList2)) {
                        if (in_array($userInfo['privilege_id'], $privilegeIdList2)) {
                            //跳过销售员转交下单人的步骤
                            //修改状态
                            $customerOrderPriceObj = \App\Eloquent\Ygt\CustomerOrderPrice::firstOrNew(['customer_order_id' => $customerOrderId]);
                            $tmpInsterRow = [
                                'customer_order_id' => $customerOrderId,
                                'sale_uid' => $userId,
//                                'status' => 2,//状态2 下单人定价格
                            ];
                            $customerOrderPriceObj->fill($tmpInsterRow);
                            $customerOrderPriceObj->save();

                            $customerOrderPirceArr = [
                                'price_tips' => '单价',//订单价格前的文字提示
                                'price' => '',//订单价格
                                'is_edit' => 1,//是否可编辑
                                'text_color' => '#000000',//字体颜色
                            ];

                            //其他价格填写
                            $otherOrderPriceList = [
                                [
                                    'tips' => '版费类型',//字段文字提示
                                    'filed_name' => 'edition_fee_type',//字段名称
                                    'default_value' => '',//默认值（展示的值）
                                    'default_select_id' => '',//默认ID（展示的值）
                                    'is_edit' => 1,//是否可编辑，1-允许 0-禁止
                                    'placeholder' => '请输入版费类型',//占位提示字符
                                    'is_change' => 0,//是否有修改
                                    'is_show' => 0,//是否显示 1-显示 0-隐藏
                                    'select_list' => $dealEditionFeeTypeList,//可以选择的值
                                    'type' => 'select',//类型select-选择 type-文字
                                ],
                                [
                                    'tips' => '版费',//字段文字提示
                                    'filed_name' => 'edition_fee',//字段名称
                                    'default_value' => '',//默认值（展示的值）
                                    'is_edit' => 1,//是否可编辑，1-允许 0-禁止
                                    'placeholder' => '请输入版费',//占位提示字符
                                    'is_change' => 0,//是否有修改
                                    'is_show' => 1,//是否显示 1-显示 0-隐藏
                                    'type' => 'text',//类型select-选择 text-文字
                                ],
                                [
                                    'tips' => '运费',//字段文字提示
                                    'filed_name' => 'freight_fee',//字段名称
                                    'default_value' => '',//默认值（展示的值）
                                    'is_edit' => 1,//是否可编辑，1-允许 0-禁止
                                    'placeholder' => '请输入运费',//占位提示字符
                                    'is_change' => 0,//是否有修改
                                    'is_show' => 1,//是否显示 1-显示 0-隐藏
                                    'type' => 'text',//类型select-选择 text-文字
                                ],
                                [
                                    'tips' => '税点',//字段文字提示
                                    'filed_name' => 'tax_point',//字段名称
                                    'default_value' => '',//默认值（展示的值）
                                    'is_edit' => 1,//是否可编辑，1-允许 0-禁止
                                    'placeholder' => '请输入税点',//占位提示字符
                                    'is_change' => 0,//是否有修改
                                    'is_show' => 1,//是否显示 1-显示 0-隐藏
                                    'type' => 'text',//类型select-选择 text-文字
                                ],
                            ];

                            $showPriceFiled = 1;
                            $editCustomerOrder = 1;
                            $submitButtonList[] = [
                                'button_name' => '确认',
                                'deal_type' => 'singlepersonSubmitPrices',
                                'check_field_data' => '小秘书温馨提示：您确认要将此价格发给客户吗？',//如果已经修改了价格的提示
                            ];
                            //新增按钮-直接确定价格（主要针对客商没有APP的时候，线下确认好价格后，直接确定订单价格） 20180702 zhuyujun
                            $submitButtonList[] = [
                                'button_name' => '签署',
                                'deal_type' => 'directConfirmPrice',
                                'check_field_data' => '小秘书温馨提示：确定直接确认价格吗？',
                            ];

                        } else {
//                            $showPriceFiled = 0;
//                            $editCustomerOrder = 1;
//
//                            $submitButtonList[] = [
//                                'button_name' => '报价给客户',
//                                'is_refresh' => 1,
//                                'deal_type' => 'directPrice',
//                            ];
                            $customerOrderPirceArr = [
                                'price_tips' => '单价',//订单价格前的文字提示
                                'price' => $customerOrderPriceRow['sale_price'],//订单价格
                                'is_edit' => 1,//是否可编辑
                                'text_color' => '#FF7E50',//字体颜色
                            ];


                            //其他价格填写
                            $otherOrderPriceList = [
                                [
                                    'tips' => '版费类型',//字段文字提示
                                    'filed_name' => 'edition_fee_type',//字段名称
                                    'default_value' => isset($editionFeeTypeList[$customerOrderPriceRow['edition_fee_type']]) ? $editionFeeTypeList[$customerOrderPriceRow['edition_fee_type']] : '',//默认值（展示的值）
                                    'default_select_id' => $customerOrderPriceRow['edition_fee_type'] ? $customerOrderPriceRow['edition_fee_type'] : '',//默认ID（展示的值）
                                    'is_edit' => 1,//是否可编辑，1-允许 0-禁止
                                    'placeholder' => '请输入版费类型',//占位提示字符
                                    'is_change' => 0,//是否有修改
                                    'is_show' => 0,//是否显示 1-显示 0-隐藏
                                    'select_list' => $dealEditionFeeTypeList,//可以选择的值
                                    'type' => 'select',//类型 select-选择 text-文字
                                ],
                                [
                                    'tips' => '版费',//字段文字提示
                                    'filed_name' => 'edition_fee',//字段名称
                                    'default_value' => $customerOrderPriceRow['edition_fee'],//默认值（展示的值）
                                    'is_edit' => 1,//是否可编辑，1-允许 0-禁止
                                    'placeholder' => '请输入版费',//占位提示字符
                                    'is_change' => (\App\Eloquent\Ygt\CustomerOrderDealUpdateLog::where(['customer_order_id' => $customerOrderId, 'deal_field_name' => 'edition_fee'])->first()) ? 1 : 0,//是否有修改
//                                'is_show' => ($customerOrderPriceRow['edition_fee_type'] == 3) ? 0 : 1,//是否显示 1-显示 0-隐藏
                                    'is_show' => 1,//是否显示 1-显示 0-隐藏
                                    'type' => 'text',//类型 select-选择 text-文字
                                ],
                                [
                                    'tips' => '运费',//字段文字提示
                                    'filed_name' => 'freight_fee',//字段名称
                                    'default_value' => $customerOrderPriceRow['freight_fee'],//默认值（展示的值）
                                    'is_edit' => 1,//是否可编辑，1-允许 0-禁止
                                    'placeholder' => '请输入运费',//占位提示字符
                                    'is_change' => (\App\Eloquent\Ygt\CustomerOrderDealUpdateLog::where(['customer_order_id' => $customerOrderId, 'deal_field_name' => 'freight_fee'])->first()) ? 1 : 0,//是否有修改
                                    'is_show' => 1,//是否显示 1-显示 0-隐藏
                                    'type' => 'text',//类型 select-选择 text-文字
                                ],
                                [
                                    'tips' => '税点',//字段文字提示
                                    'filed_name' => 'tax_point',//字段名称
                                    'default_value' => $customerOrderPriceRow['tax_point'],//默认值（展示的值）
                                    'is_edit' => 1,//是否可编辑，1-允许 0-禁止
                                    'placeholder' => '请输入税点',//占位提示字符
                                    'is_change' => (\App\Eloquent\Ygt\CustomerOrderDealUpdateLog::where(['customer_order_id' => $customerOrderId, 'deal_field_name' => 'tax_point'])->first()) ? 1 : 0,//是否有修改
                                    'is_show' => 1,//是否显示 1-显示 0-隐藏
                                    'type' => 'text',//类型 select-选择 text-文字
                                ],
                            ];
                            $showPriceFiled = 1;
                            $editCustomerOrder = 1;
                            $submitButtonList[] = [
//                            'button_name' => '转交客户确认',
                                'button_name' => '报价客户',
                                'deal_type' => 'transferToCustomer',
                                'check_price' => '小秘书温馨提示：您还没有设置销售报价，要确认将成本价报给客户吗？',//需要判断有没有修改价格
                                'update_price_tips' => '小秘书温馨提示：您确认要将此价格发给客户吗？',//如果已经修改了价格的提示
                            ];


                            //新增按钮-直接确定价格（主要针对客商没有APP的时候，线下确认好价格后，直接确定订单价格） 20180702 zhuyujun
                            $submitButtonList[] = [
                                'button_name' => '签署',
                                'deal_type' => 'directConfirmPrice',
                                'check_field_data' => '小秘书温馨提示：确定直接确认价格吗？',
                            ];

                        }


                    }

                    break;
                case '2':
                    ////下单人填写报价（成本价）阶段
                    //判断用户是否为下单人
                    $privilegeIdList = \App\Engine\OrderEngine::getPrivilegeByNode($companyId, 1);
                    if (in_array($userInfo['privilege_id'], $privilegeIdList)) {
                        $customerOrderPirceArr = [
                            'price_tips' => '单价',//订单价格前的文字提示
                            'price' => '',//订单价格
                            'is_edit' => 1,//是否可编辑
                            'text_color' => '#000000',//字体颜色
                        ];

                        //其他价格填写
                        $otherOrderPriceList = [
                        ];

                        $showPriceFiled = 1;
                        $editCustomerOrder = 1;
                    }

                    //新加逻辑，销售员依旧能报价给客户
                    //判断用户是否为销售员
                    $privilegeIdList = \App\Engine\OrderEngine::getPrivilegeByNode($companyId, 13);
                    if (in_array($userInfo['privilege_id'], $privilegeIdList)) {
//                        $showPriceFiled = 0;
//                        $editCustomerOrder = 1;
//
//                        $submitButtonList[] = [
//                            'button_name' => '报价给客户',
//                            'is_refresh' => 1,
//                            'deal_type' => 'directPrice',
//                        ];
                        $customerOrderPirceArr = [
                            'price_tips' => '单价',//订单价格前的文字提示
                            'price' => $customerOrderPriceRow['sale_price'],//订单价格
                            'is_edit' => 1,//是否可编辑
                            'text_color' => '#FF7E50',//字体颜色
                        ];


                        //其他价格填写
                        $otherOrderPriceList = [
                            [
                                'tips' => '版费类型',//字段文字提示
                                'filed_name' => 'edition_fee_type',//字段名称
                                'default_value' => isset($editionFeeTypeList[$customerOrderPriceRow['edition_fee_type']]) ? $editionFeeTypeList[$customerOrderPriceRow['edition_fee_type']] : '',//默认值（展示的值）
                                'default_select_id' => $customerOrderPriceRow['edition_fee_type'] ? $customerOrderPriceRow['edition_fee_type'] : '',//默认ID（展示的值）
                                'is_edit' => 1,//是否可编辑，1-允许 0-禁止
                                'placeholder' => '请输入版费类型',//占位提示字符
                                'is_change' => 0,//是否有修改
                                'is_show' => 0,//是否显示 1-显示 0-隐藏
                                'select_list' => $dealEditionFeeTypeList,//可以选择的值
                                'type' => 'select',//类型 select-选择 text-文字
                            ],
                            [
                                'tips' => '版费',//字段文字提示
                                'filed_name' => 'edition_fee',//字段名称
                                'default_value' => $customerOrderPriceRow['edition_fee'],//默认值（展示的值）
                                'is_edit' => 1,//是否可编辑，1-允许 0-禁止
                                'placeholder' => '请输入版费',//占位提示字符
                                'is_change' => (\App\Eloquent\Ygt\CustomerOrderDealUpdateLog::where(['customer_order_id' => $customerOrderId, 'deal_field_name' => 'edition_fee'])->first()) ? 1 : 0,//是否有修改
//                                'is_show' => ($customerOrderPriceRow['edition_fee_type'] == 3) ? 0 : 1,//是否显示 1-显示 0-隐藏
                                'is_show' => 1,//是否显示 1-显示 0-隐藏
                                'type' => 'text',//类型 select-选择 text-文字
                            ],
                            [
                                'tips' => '运费',//字段文字提示
                                'filed_name' => 'freight_fee',//字段名称
                                'default_value' => $customerOrderPriceRow['freight_fee'],//默认值（展示的值）
                                'is_edit' => 1,//是否可编辑，1-允许 0-禁止
                                'placeholder' => '请输入运费',//占位提示字符
                                'is_change' => (\App\Eloquent\Ygt\CustomerOrderDealUpdateLog::where(['customer_order_id' => $customerOrderId, 'deal_field_name' => 'freight_fee'])->first()) ? 1 : 0,//是否有修改
                                'is_show' => 1,//是否显示 1-显示 0-隐藏
                                'type' => 'text',//类型 select-选择 text-文字
                            ],
                            [
                                'tips' => '税点',//字段文字提示
                                'filed_name' => 'tax_point',//字段名称
                                'default_value' => $customerOrderPriceRow['tax_point'],//默认值（展示的值）
                                'is_edit' => 1,//是否可编辑，1-允许 0-禁止
                                'placeholder' => '请输入税点',//占位提示字符
                                'is_change' => (\App\Eloquent\Ygt\CustomerOrderDealUpdateLog::where(['customer_order_id' => $customerOrderId, 'deal_field_name' => 'tax_point'])->first()) ? 1 : 0,//是否有修改
                                'is_show' => 1,//是否显示 1-显示 0-隐藏
                                'type' => 'text',//类型 select-选择 text-文字
                            ],
                        ];
                        $showPriceFiled = 1;
                        $editCustomerOrder = 1;
                        $submitButtonList[] = [
//                            'button_name' => '转交客户确认',
                            'button_name' => '报价客户',
                            'deal_type' => 'transferToCustomer',
                            'check_price' => '小秘书温馨提示：您还没有设置销售报价，要确认将成本价报给客户吗？',//需要判断有没有修改价格
                            'update_price_tips' => '小秘书温馨提示：您确认要将此价格发给客户吗？',//如果已经修改了价格的提示
                        ];


                        //新增按钮-直接确定价格（主要针对客商没有APP的时候，线下确认好价格后，直接确定订单价格） 20180702 zhuyujun
                        $submitButtonList[] = [
                            'button_name' => '签署',
                            'deal_type' => 'directConfirmPrice',
                            'check_field_data' => '小秘书温馨提示：确定直接确认价格吗？',
                        ];
                    }

                    break;
                case '3':
                    ////销售员提交报价给客户阶段
                    if ($userId == $customerOrderPriceRow['sale_uid']) {
                        $customerOrderPirceArr = [
                            'price_tips' => '单价',//订单价格前的文字提示
                            'price' => $customerOrderPriceRow['sale_price'],//订单价格
                            'is_edit' => 1,//是否可编辑
                            'text_color' => '#FF7E50',//字体颜色
                        ];


                        //其他价格填写
                        $otherOrderPriceList = [
                            [
                                'tips' => '版费类型',//字段文字提示
                                'filed_name' => 'edition_fee_type',//字段名称
                                'default_value' => isset($editionFeeTypeList[$customerOrderPriceRow['edition_fee_type']]) ? $editionFeeTypeList[$customerOrderPriceRow['edition_fee_type']] : '',//默认值（展示的值）
                                'default_select_id' => $customerOrderPriceRow['edition_fee_type'] ? $customerOrderPriceRow['edition_fee_type'] : '',//默认ID（展示的值）
                                'is_edit' => 1,//是否可编辑，1-允许 0-禁止
                                'placeholder' => '请输入版费类型',//占位提示字符
                                'is_change' => 0,//是否有修改
                                'is_show' => 0,//是否显示 1-显示 0-隐藏
                                'select_list' => $dealEditionFeeTypeList,//可以选择的值
                                'type' => 'select',//类型 select-选择 text-文字
                            ],
                            [
                                'tips' => '版费',//字段文字提示
                                'filed_name' => 'edition_fee',//字段名称
                                'default_value' => $customerOrderPriceRow['edition_fee'],//默认值（展示的值）
                                'is_edit' => 1,//是否可编辑，1-允许 0-禁止
                                'placeholder' => '请输入版费',//占位提示字符
                                'is_change' => (\App\Eloquent\Ygt\CustomerOrderDealUpdateLog::where(['customer_order_id' => $customerOrderId, 'deal_field_name' => 'edition_fee'])->first()) ? 1 : 0,//是否有修改
//                                'is_show' => ($customerOrderPriceRow['edition_fee_type'] == 3) ? 0 : 1,//是否显示 1-显示 0-隐藏
                                'is_show' => 1,//是否显示 1-显示 0-隐藏
                                'type' => 'text',//类型 select-选择 text-文字
                            ],
                            [
                                'tips' => '运费',//字段文字提示
                                'filed_name' => 'freight_fee',//字段名称
                                'default_value' => $customerOrderPriceRow['freight_fee'],//默认值（展示的值）
                                'is_edit' => 1,//是否可编辑，1-允许 0-禁止
                                'placeholder' => '请输入运费',//占位提示字符
                                'is_change' => (\App\Eloquent\Ygt\CustomerOrderDealUpdateLog::where(['customer_order_id' => $customerOrderId, 'deal_field_name' => 'freight_fee'])->first()) ? 1 : 0,//是否有修改
                                'is_show' => 1,//是否显示 1-显示 0-隐藏
                                'type' => 'text',//类型 select-选择 text-文字
                            ],
                            [
                                'tips' => '税点',//字段文字提示
                                'filed_name' => 'tax_point',//字段名称
                                'default_value' => $customerOrderPriceRow['tax_point'],//默认值（展示的值）
                                'is_edit' => 1,//是否可编辑，1-允许 0-禁止
                                'placeholder' => '请输入税点',//占位提示字符
                                'is_change' => (\App\Eloquent\Ygt\CustomerOrderDealUpdateLog::where(['customer_order_id' => $customerOrderId, 'deal_field_name' => 'tax_point'])->first()) ? 1 : 0,//是否有修改
                                'is_show' => 1,//是否显示 1-显示 0-隐藏
                                'type' => 'text',//类型 select-选择 text-文字
                            ],
                        ];
                        $showPriceFiled = 1;
                        $editCustomerOrder = 1;
                        $submitButtonList[] = [
//                            'button_name' => '转交客户确认',
                            'button_name' => '报价客户',
                            'deal_type' => 'transferToCustomer',
                            'check_price' => '小秘书温馨提示：您还没有设置销售报价，要确认将成本价报给客户吗？',//需要判断有没有修改价格
                            'update_price_tips' => '小秘书温馨提示：您确认要将此价格发给客户吗？',//如果已经修改了价格的提示
                        ];


                        //新增按钮-直接确定价格（主要针对客商没有APP的时候，线下确认好价格后，直接确定订单价格） 20180702 zhuyujun
                        $submitButtonList[] = [
                            'button_name' => '签署',
                            'deal_type' => 'directConfirmPrice',
                            'check_field_data' => '小秘书温馨提示：确定直接确认价格吗？',
                        ];

                    } else {

                        //判断用户是否为下单人
                        $privilegeIdList1 = \App\Engine\OrderEngine::getPrivilegeByNode($companyId, 1);
                        //判断用户是否为销售员
                        $privilegeIdList13 = \App\Engine\OrderEngine::getPrivilegeByNode($companyId, 13);

                        if (in_array($userInfo['privilege_id'], $privilegeIdList1) || in_array($userInfo['privilege_id'], $privilegeIdList13)) {
                            //是下单人或者为销售员
                            $customerOrderPirceArr = [
                                'price_tips' => '单价',//订单价格前的文字提示
                                'price' => $customerOrderPriceRow['sale_price'],//订单价格
                                'is_edit' => 2,//是否可编辑
                                'text_color' => '#FF7E50',//字体颜色
                            ];

                            //其他价格填写
                            $otherOrderPriceList = [
                            ];
                            $showPriceFiled = 1;

                        }

                    }

                    break;
                case '4':
                    ////客户确认订单价格阶段
                    if ($userId == $customerOrderPriceRow['customer_uid']) {
                        //客户确认价格界面
                        $customerOrderPirceArr = [
                            'price_tips' => '单价',//订单价格前的文字提示
                            'price' => $customerOrderPriceRow['sale_price'],//订单价格
                            'is_edit' => 1,//是否可编辑
                            'text_color' => '#FF7E50',//字体颜色
                        ];
                        //其他价格填写
                        $otherOrderPriceList = [
                            [
                                'tips' => '版费类型',//字段文字提示
                                'filed_name' => 'edition_fee_type',//字段名称
                                'default_value' => isset($editionFeeTypeList[$customerOrderPriceRow['edition_fee_type']]) ? $editionFeeTypeList[$customerOrderPriceRow['edition_fee_type']] : '',//默认值（展示的值）
                                'default_select_id' => $customerOrderPriceRow['edition_fee_type'] ? $customerOrderPriceRow['edition_fee_type'] : '',//默认ID（展示的值）
                                'is_edit' => 1,//是否可编辑，1-允许 0-禁止
                                'placeholder' => '请输入版费类型',//占位提示字符
                                'is_change' => 0,//是否有修改
                                'is_show' => 0,//是否显示 1-显示 0-隐藏
                                'select_list' => $dealEditionFeeTypeList,//可以选择的值
                                'type' => 'select',//类型 select-选择 text-文字
                            ],
                            [
                                'tips' => '版费',//字段文字提示
                                'filed_name' => 'edition_fee',//字段名称
                                'default_value' => $customerOrderPriceRow['edition_fee'],//默认值（展示的值）
                                'is_edit' => 1,//是否可编辑，1-允许 0-禁止
                                'placeholder' => '请输入版费',//占位提示字符
                                'is_change' => (\App\Eloquent\Ygt\CustomerOrderDealUpdateLog::where(['customer_order_id' => $customerOrderId, 'deal_field_name' => 'edition_fee'])->first()) ? 1 : 0,//是否有修改
//                                'is_show' => ($customerOrderPriceRow['edition_fee_type'] == 3) ? 0 : 1,//是否显示 1-显示 0-隐藏
                                'is_show' => 1,//是否显示 1-显示 0-隐藏
                                'type' => 'text',//类型 select-选择 text-文字

                            ],
                            [
                                'tips' => '运费',//字段文字提示
                                'filed_name' => 'freight_fee',//字段名称
                                'default_value' => $customerOrderPriceRow['freight_fee'],//默认值（展示的值）
                                'is_edit' => 1,//是否可编辑，1-允许 0-禁止
                                'placeholder' => '请输入运费',//占位提示字符
                                'is_change' => (\App\Eloquent\Ygt\CustomerOrderDealUpdateLog::where(['customer_order_id' => $customerOrderId, 'deal_field_name' => 'freight_fee'])->first()) ? 1 : 0,//是否有修改
                                'is_show' => 1,//是否显示 1-显示 0-隐藏
                                'type' => 'text',//类型 select-选择 text-文字
                            ],
                            [
                                'tips' => '税点',//字段文字提示
                                'filed_name' => 'tax_point',//字段名称
                                'default_value' => $customerOrderPriceRow['tax_point'],//默认值（展示的值）
                                'is_edit' => 1,//是否可编辑，1-允许 0-禁止
                                'placeholder' => '请输入税点',//占位提示字符
                                'is_change' => (\App\Eloquent\Ygt\CustomerOrderDealUpdateLog::where(['customer_order_id' => $customerOrderId, 'deal_field_name' => 'tax_point'])->first()) ? 1 : 0,//是否有修改
                                'is_show' => 1,//是否显示 1-显示 0-隐藏
                                'type' => 'text',//类型 select-选择 text-文字
                            ],
                        ];


                        $showPriceFiled = 1;
                        $editCustomerOrder = 1;
                        $submitButtonList[] = [
                            'button_name' => '提交修改',
                            'deal_type' => 'customerSubmit',
                            'submit_type' => 'reject',
                        ];
                        $submitButtonList[] = [
                            'button_name' => '签署确认',
                            'deal_type' => 'customerSubmit',
                            'submit_type' => 'agree',
                            'check_field_data' => '小秘书温馨提示：如果您确认签署此工厂报价，那么工厂报价和订单详情将不会被修改！',
                        ];

                        $topTips = [
                            'tips' => '请修改/确认订单',
                            'color' => '#FF7E50',
                        ];
                    } elseif ($userId == $customerOrderPriceRow['sale_uid']) {
                        ////销售员允许多次修改 20180731 zhuyujun
                        $customerOrderPirceArr = [
                            'price_tips' => '单价',//订单价格前的文字提示
                            'price' => $customerOrderPriceRow['sale_price'],//订单价格
                            'is_edit' => 1,//是否可编辑
                            'text_color' => '#FF7E50',//字体颜色
                        ];


                        //其他价格填写
                        $otherOrderPriceList = [
                            [
                                'tips' => '版费类型',//字段文字提示
                                'filed_name' => 'edition_fee_type',//字段名称
                                'default_value' => isset($editionFeeTypeList[$customerOrderPriceRow['edition_fee_type']]) ? $editionFeeTypeList[$customerOrderPriceRow['edition_fee_type']] : '',//默认值（展示的值）
                                'default_select_id' => $customerOrderPriceRow['edition_fee_type'] ? $customerOrderPriceRow['edition_fee_type'] : '',//默认ID（展示的值）
                                'is_edit' => 1,//是否可编辑，1-允许 0-禁止
                                'placeholder' => '请输入版费类型',//占位提示字符
                                'is_change' => 0,//是否有修改
                                'is_show' => 0,//是否显示 1-显示 0-隐藏
                                'select_list' => $dealEditionFeeTypeList,//可以选择的值
                                'type' => 'select',//类型 select-选择 text-文字
                            ],
                            [
                                'tips' => '版费',//字段文字提示
                                'filed_name' => 'edition_fee',//字段名称
                                'default_value' => $customerOrderPriceRow['edition_fee'],//默认值（展示的值）
                                'is_edit' => 1,//是否可编辑，1-允许 0-禁止
                                'placeholder' => '请输入版费',//占位提示字符
                                'is_change' => (\App\Eloquent\Ygt\CustomerOrderDealUpdateLog::where(['customer_order_id' => $customerOrderId, 'deal_field_name' => 'edition_fee'])->first()) ? 1 : 0,//是否有修改
//                                'is_show' => ($customerOrderPriceRow['edition_fee_type'] == 3) ? 0 : 1,//是否显示 1-显示 0-隐藏
                                'is_show' => 1,//是否显示 1-显示 0-隐藏
                                'type' => 'text',//类型 select-选择 text-文字
                            ],
                            [
                                'tips' => '运费',//字段文字提示
                                'filed_name' => 'freight_fee',//字段名称
                                'default_value' => $customerOrderPriceRow['freight_fee'],//默认值（展示的值）
                                'is_edit' => 1,//是否可编辑，1-允许 0-禁止
                                'placeholder' => '请输入运费',//占位提示字符
                                'is_change' => (\App\Eloquent\Ygt\CustomerOrderDealUpdateLog::where(['customer_order_id' => $customerOrderId, 'deal_field_name' => 'freight_fee'])->first()) ? 1 : 0,//是否有修改
                                'is_show' => 1,//是否显示 1-显示 0-隐藏
                                'type' => 'text',//类型 select-选择 text-文字
                            ],
                            [
                                'tips' => '税点',//字段文字提示
                                'filed_name' => 'tax_point',//字段名称
                                'default_value' => $customerOrderPriceRow['tax_point'],//默认值（展示的值）
                                'is_edit' => 1,//是否可编辑，1-允许 0-禁止
                                'placeholder' => '请输入税点',//占位提示字符
                                'is_change' => (\App\Eloquent\Ygt\CustomerOrderDealUpdateLog::where(['customer_order_id' => $customerOrderId, 'deal_field_name' => 'tax_point'])->first()) ? 1 : 0,//是否有修改
                                'is_show' => 1,//是否显示 1-显示 0-隐藏
                                'type' => 'text',//类型 select-选择 text-文字
                            ],
                        ];
                        $showPriceFiled = 1;
                        $editCustomerOrder = 1;
                        $submitButtonList[] = [
//                            'button_name' => '转交客户确认',
                            'button_name' => '报价客户',
                            'deal_type' => 'transferToCustomer',
                            'check_price' => '小秘书温馨提示：您还没有设置销售报价，要确认将成本价报给客户吗？',//需要判断有没有修改价格
                            'update_price_tips' => '小秘书温馨提示：您确认要将此价格发给客户吗？',//如果已经修改了价格的提示
                        ];

                        //新增按钮-直接确定价格（主要针对客商没有APP的时候，线下确认好价格后，直接确定订单价格） 20180702 zhuyujun
                        $submitButtonList[] = [
                            'button_name' => '签署',
                            'deal_type' => 'directConfirmPrice',
                            'check_field_data' => '小秘书温馨提示：确定直接确认价格吗？',
                        ];

                    } else {
                        $customerOrderPirceArr = [
                            'price_tips' => '单价',//订单价格前的文字提示
                            'price' => $customerOrderPriceRow['sale_price'],//订单价格
                            'is_edit' => 2,//是否可编辑
                            'text_color' => '#FF7E50',//字体颜色
                        ];


                        //其他价格填写
                        $otherOrderPriceList = [
                            [
                                'tips' => '版费类型',//字段文字提示
                                'filed_name' => 'edition_fee_type',//字段名称
                                'default_value' => isset($editionFeeTypeList[$customerOrderPriceRow['edition_fee_type']]) ? $editionFeeTypeList[$customerOrderPriceRow['edition_fee_type']] : '',//默认值（展示的值）
                                'default_select_id' => $customerOrderPriceRow['edition_fee_type'] ? $customerOrderPriceRow['edition_fee_type'] : '',//默认ID（展示的值）
                                'is_edit' => 0,//是否可编辑，1-允许 0-禁止
                                'placeholder' => '请输入版费类型',//占位提示字符
                                'is_change' => 0,//是否有修改
                                'is_show' => 0,//是否显示 1-显示 0-隐藏
                                'select_list' => $dealEditionFeeTypeList,//可以选择的值
                                'type' => 'select',//类型 select-选择 text-文字
                            ],
                            [
                                'tips' => '版费',//字段文字提示
                                'filed_name' => 'edition_fee',//字段名称
                                'default_value' => $customerOrderPriceRow['edition_fee'],//默认值（展示的值）
                                'is_edit' => 0,//是否可编辑，1-允许 0-禁止
                                'placeholder' => '',//占位提示字符
                                'is_change' => (\App\Eloquent\Ygt\CustomerOrderDealUpdateLog::where(['customer_order_id' => $customerOrderId, 'deal_field_name' => 'edition_fee'])->first()) ? 1 : 0,//是否有修改
//                                'is_show' => ($customerOrderPriceRow['edition_fee_type'] == 3) ? 0 : 1,//是否显示 1-显示 0-隐藏
                                'is_show' => 1,//是否显示 1-显示 0-隐藏
                                'type' => 'text',//类型 select-选择 text-文字
                            ],
                            [
                                'tips' => '运费',//字段文字提示
                                'filed_name' => 'freight_fee',//字段名称
                                'default_value' => $customerOrderPriceRow['freight_fee'],//默认值（展示的值）
                                'is_edit' => 0,//是否可编辑，1-允许 0-禁止
                                'placeholder' => '',//占位提示字符
                                'is_change' => (\App\Eloquent\Ygt\CustomerOrderDealUpdateLog::where(['customer_order_id' => $customerOrderId, 'deal_field_name' => 'freight_fee'])->first()) ? 1 : 0,//是否有修改
                                'is_show' => 1,//是否显示 1-显示 0-隐藏
                                'type' => 'text',//类型 select-选择 text-文字
                            ],
                            [
                                'tips' => '税点',//字段文字提示
                                'filed_name' => 'tax_point',//字段名称
                                'default_value' => $customerOrderPriceRow['tax_point'],//默认值（展示的值）
                                'is_edit' => 0,//是否可编辑，1-允许 0-禁止
                                'placeholder' => '',//占位提示字符
                                'is_change' => (\App\Eloquent\Ygt\CustomerOrderDealUpdateLog::where(['customer_order_id' => $customerOrderId, 'deal_field_name' => 'tax_point'])->first()) ? 1 : 0,//是否有修改
                                'is_show' => 1,//是否显示 1-显示 0-隐藏
                                'type' => 'text',//类型 select-选择 text-文字
                            ],
                        ];


                        $showPriceFiled = 1;
                    }

                    break;
                case '5':
                    ////销售员确认订单价格阶段
                    if ($userId == $customerOrderPriceRow['sale_uid']) {
                        //销售员确认价格界面
                        $customerOrderPirceArr = [
                            'price_tips' => '单价',//订单价格前的文字提示
                            'price' => $customerOrderPriceRow['customer_price'],//订单价格
                            'is_edit' => 1,//是否可编辑
                            'text_color' => '#FF7E50',//字体颜色
                        ];


                        //其他价格填写
                        $otherOrderPriceList = [
                            [
                                'tips' => '版费类型',//字段文字提示
                                'filed_name' => 'edition_fee_type',//字段名称
                                'default_value' => isset($editionFeeTypeList[$customerOrderPriceRow['edition_fee_type']]) ? $editionFeeTypeList[$customerOrderPriceRow['edition_fee_type']] : '',//默认值（展示的值）
                                'default_select_id' => $customerOrderPriceRow['edition_fee_type'] ? $customerOrderPriceRow['edition_fee_type'] : '',//默认ID（展示的值）
                                'is_edit' => 1,//是否可编辑，1-允许 0-禁止
                                'placeholder' => '请输入版费类型',//占位提示字符
                                'is_change' => 0,//是否有修改
                                'is_show' => 0,//是否显示 1-显示 0-隐藏
                                'select_list' => $dealEditionFeeTypeList,//可以选择的值
                                'type' => 'select',//类型 select-选择 text-文字
                            ],
                            [
                                'tips' => '版费',//字段文字提示
                                'filed_name' => 'edition_fee',//字段名称
                                'default_value' => $customerOrderPriceRow['edition_fee'],//默认值（展示的值）
                                'is_edit' => 1,//是否可编辑，1-允许 0-禁止
                                'placeholder' => '请输入版费',//占位提示字符
                                'is_change' => (\App\Eloquent\Ygt\CustomerOrderDealUpdateLog::where(['customer_order_id' => $customerOrderId, 'deal_field_name' => 'edition_fee'])->first()) ? 1 : 0,//是否有修改
//                                'is_show' => ($customerOrderPriceRow['edition_fee_type'] == 3) ? 0 : 1,//是否显示 1-显示 0-隐藏
                                'is_show' => 1,//是否显示 1-显示 0-隐藏
                                'type' => 'text',//类型 select-选择 text-文字
                            ],
                            [
                                'tips' => '运费',//字段文字提示
                                'filed_name' => 'freight_fee',//字段名称
                                'default_value' => $customerOrderPriceRow['freight_fee'],//默认值（展示的值）
                                'is_edit' => 1,//是否可编辑，1-允许 0-禁止
                                'placeholder' => '请输入运费',//占位提示字符
                                'is_change' => (\App\Eloquent\Ygt\CustomerOrderDealUpdateLog::where(['customer_order_id' => $customerOrderId, 'deal_field_name' => 'freight_fee'])->first()) ? 1 : 0,//是否有修改
                                'is_show' => 1,//是否显示 1-显示 0-隐藏
                                'type' => 'text',//类型 select-选择 text-文字
                            ],
                            [
                                'tips' => '税点',//字段文字提示
                                'filed_name' => 'tax_point',//字段名称
                                'default_value' => $customerOrderPriceRow['tax_point'],//默认值（展示的值）
                                'is_edit' => 1,//是否可编辑，1-允许 0-禁止
                                'placeholder' => '请输入税点',//占位提示字符
                                'is_change' => (\App\Eloquent\Ygt\CustomerOrderDealUpdateLog::where(['customer_order_id' => $customerOrderId, 'deal_field_name' => 'tax_point'])->first()) ? 1 : 0,//是否有修改
                                'is_show' => 1,//是否显示 1-显示 0-隐藏
                                'type' => 'text',//类型 select-选择 text-文字
                            ],
                        ];

                        $showPriceFiled = 1;
                        $editCustomerOrder = 1;
                        $submitButtonList[] = [
                            'button_name' => '提交修改',
                            'deal_type' => 'sellerSubmit',
                            'submit_type' => 'reject',
                        ];
                        $submitButtonList[] = [
                            'button_name' => '签署确认',
                            'deal_type' => 'sellerSubmit',
                            'submit_type' => 'agree',
                            'check_field_data' => '小秘书温馨提示：如果您确认签署此客户订单，那么客户订单详情将不会被修改！',
                        ];

                        $topTips = [
                            'tips' => '请修改/确认订单',
                            'color' => '#FF7E50',
                        ];
                    } else {
                        //订单已确认
                        $customerOrderPirceArr = [
                            'price_tips' => '单价',//订单价格前的文字提示
                            'price' => $customerOrderPriceRow['customer_price'],//订单价格
                            'is_edit' => 2,//是否可编辑
                            'text_color' => '#FF7E50',//字体颜色
                        ];

                        //其他价格填写
                        $otherOrderPriceList = [
                            [
                                'tips' => '版费类型',//字段文字提示
                                'filed_name' => 'edition_fee_type',//字段名称
                                'default_value' => isset($editionFeeTypeList[$customerOrderPriceRow['edition_fee_type']]) ? $editionFeeTypeList[$customerOrderPriceRow['edition_fee_type']] : '',//默认值（展示的值）
                                'default_select_id' => $customerOrderPriceRow['edition_fee_type'] ? $customerOrderPriceRow['edition_fee_type'] : '',//默认ID（展示的值）
                                'is_edit' => 0,//是否可编辑，1-允许 0-禁止
                                'placeholder' => '请输入版费类型',//占位提示字符
                                'is_change' => 0,//是否有修改
                                'is_show' => 0,//是否显示 1-显示 0-隐藏
                                'select_list' => $dealEditionFeeTypeList,//可以选择的值
                                'type' => 'select',//类型 select-选择 text-文字
                            ],
                            [
                                'tips' => '版费',//字段文字提示
                                'filed_name' => 'edition_fee',//字段名称
                                'default_value' => $customerOrderPriceRow['edition_fee'],//默认值（展示的值）
                                'is_edit' => 0,//是否可编辑，1-允许 0-禁止
                                'placeholder' => '请输入版费',//占位提示字符
                                'is_change' => (\App\Eloquent\Ygt\CustomerOrderDealUpdateLog::where(['customer_order_id' => $customerOrderId, 'deal_field_name' => 'edition_fee'])->first()) ? 1 : 0,//是否有修改
//                                'is_show' => ($customerOrderPriceRow['edition_fee_type'] == 3) ? 0 : 1,//是否显示 1-显示 0-隐藏
                                'is_show' => 1,//是否显示 1-显示 0-隐藏
                                'type' => 'text',//类型 select-选择 text-文字
                            ],
                            [
                                'tips' => '运费',//字段文字提示
                                'filed_name' => 'freight_fee',//字段名称
                                'default_value' => $customerOrderPriceRow['freight_fee'],//默认值（展示的值）
                                'is_edit' => 0,//是否可编辑，1-允许 0-禁止
                                'placeholder' => '',//占位提示字符
                                'is_change' => (\App\Eloquent\Ygt\CustomerOrderDealUpdateLog::where(['customer_order_id' => $customerOrderId, 'deal_field_name' => 'freight_fee'])->first()) ? 1 : 0,//是否有修改
                                'is_show' => 1,//是否显示 1-显示 0-隐藏
                                'type' => 'text',//类型 select-选择 text-文字
                            ],
                            [
                                'tips' => '税点',//字段文字提示
                                'filed_name' => 'tax_point',//字段名称
                                'default_value' => $customerOrderPriceRow['tax_point'],//默认值（展示的值）
                                'is_edit' => 0,//是否可编辑，1-允许 0-禁止
                                'placeholder' => '',//占位提示字符
                                'is_change' => (\App\Eloquent\Ygt\CustomerOrderDealUpdateLog::where(['customer_order_id' => $customerOrderId, 'deal_field_name' => 'tax_point'])->first()) ? 1 : 0,//是否有修改
                                'is_show' => 1,//是否显示 1-显示 0-隐藏
                                'type' => 'text',//类型 select-选择 text-文字
                            ],
                        ];


                        $showPriceFiled = 1;
                        $editCustomerOrder = 0;

                    }

                    break;
                case '6':
                    ////客户确认订单价格阶段（销售员拒绝了价格）
                    //同status = 6
                    if ($userId == $customerOrderPriceRow['customer_uid']) {
                        //客户确认价格界面
                        $customerOrderPirceArr = [
                            'price_tips' => '单价',//订单价格前的文字提示
                            'price' => $customerOrderPriceRow['sale_price'],//订单价格
                            'is_edit' => 1,//是否可编辑
                            'text_color' => '#FF7E50',//字体颜色
                        ];


                        //其他价格填写
                        $otherOrderPriceList = [
                            [
                                'tips' => '版费类型',//字段文字提示
                                'filed_name' => 'edition_fee_type',//字段名称
                                'default_value' => isset($editionFeeTypeList[$customerOrderPriceRow['edition_fee_type']]) ? $editionFeeTypeList[$customerOrderPriceRow['edition_fee_type']] : '',//默认值（展示的值）
                                'default_select_id' => $customerOrderPriceRow['edition_fee_type'] ? $customerOrderPriceRow['edition_fee_type'] : '',//默认ID（展示的值）
                                'is_edit' => 1,//是否可编辑，1-允许 0-禁止
                                'placeholder' => '请输入版费类型',//占位提示字符
                                'is_change' => 0,//是否有修改
                                'is_show' => 0,//是否显示 1-显示 0-隐藏
                                'select_list' => $dealEditionFeeTypeList,//可以选择的值
                                'type' => 'select',//类型 select-选择 text-文字
                            ],
                            [
                                'tips' => '版费',//字段文字提示
                                'filed_name' => 'edition_fee',//字段名称
                                'default_value' => $customerOrderPriceRow['edition_fee'],//默认值（展示的值）
                                'is_edit' => 1,//是否可编辑，1-允许 0-禁止
                                'placeholder' => '请输入版费',//占位提示字符
                                'is_change' => (\App\Eloquent\Ygt\CustomerOrderDealUpdateLog::where(['customer_order_id' => $customerOrderId, 'deal_field_name' => 'edition_fee'])->first()) ? 1 : 0,//是否有修改
//                                'is_show' => ($customerOrderPriceRow['edition_fee_type'] == 3) ? 0 : 1,//是否显示 1-显示 0-隐藏
                                'is_show' => 1,//是否显示 1-显示 0-隐藏
                                'type' => 'text',//类型 select-选择 text-文字
                            ],
                            [
                                'tips' => '运费',//字段文字提示
                                'filed_name' => 'freight_fee',//字段名称
                                'default_value' => $customerOrderPriceRow['freight_fee'],//默认值（展示的值）
                                'is_edit' => 1,//是否可编辑，1-允许 0-禁止
                                'placeholder' => '请输入运费',//占位提示字符
                                'is_change' => (\App\Eloquent\Ygt\CustomerOrderDealUpdateLog::where(['customer_order_id' => $customerOrderId, 'deal_field_name' => 'freight_fee'])->first()) ? 1 : 0,//是否有修改
                                'is_show' => 1,//是否显示 1-显示 0-隐藏
                                'type' => 'text',//类型 select-选择 text-文字
                            ],
                            [
                                'tips' => '税点',//字段文字提示
                                'filed_name' => 'tax_point',//字段名称
                                'default_value' => $customerOrderPriceRow['tax_point'],//默认值（展示的值）
                                'is_edit' => 1,//是否可编辑，1-允许 0-禁止
                                'placeholder' => '请输入税点',//占位提示字符
                                'is_change' => (\App\Eloquent\Ygt\CustomerOrderDealUpdateLog::where(['customer_order_id' => $customerOrderId, 'deal_field_name' => 'tax_point'])->first()) ? 1 : 0,//是否有修改
                                'is_show' => 1,//是否显示 1-显示 0-隐藏
                                'type' => 'text',//类型 select-选择 text-文字
                            ],
                        ];

                        $showPriceFiled = 1;
                        $editCustomerOrder = 1;
                        $submitButtonList[] = [
                            'button_name' => '提交修改',
                            'deal_type' => 'customerSubmit',
                            'submit_type' => 'reject',
                        ];
                        $submitButtonList[] = [
                            'button_name' => '签署确认',
                            'deal_type' => 'customerSubmit',
                            'submit_type' => 'agree',
                            'check_field_data' => '小秘书温馨提示：如果您确认签署此工厂报价，那么工厂报价和订单详情将不会被修改！',
                        ];

                        $topTips = [
                            'tips' => '请修改/确认订单',
                            'color' => '#FF7E50',
                        ];
                    } elseif ($userId == $customerOrderPriceRow['sale_uid']) {
                        ////销售员允许多次修改 20180731 zhuyujun
                        //销售员确认价格界面
                        $customerOrderPirceArr = [
                            'price_tips' => '单价',//订单价格前的文字提示
                            'price' => $customerOrderPriceRow['sale_price'],//订单价格
                            'is_edit' => 1,//是否可编辑
                            'text_color' => '#FF7E50',//字体颜色
                        ];


                        //其他价格填写
                        $otherOrderPriceList = [
                            [
                                'tips' => '版费类型',//字段文字提示
                                'filed_name' => 'edition_fee_type',//字段名称
                                'default_value' => isset($editionFeeTypeList[$customerOrderPriceRow['edition_fee_type']]) ? $editionFeeTypeList[$customerOrderPriceRow['edition_fee_type']] : '',//默认值（展示的值）
                                'default_select_id' => $customerOrderPriceRow['edition_fee_type'] ? $customerOrderPriceRow['edition_fee_type'] : '',//默认ID（展示的值）
                                'is_edit' => 1,//是否可编辑，1-允许 0-禁止
                                'placeholder' => '请输入版费类型',//占位提示字符
                                'is_change' => 0,//是否有修改
                                'is_show' => 0,//是否显示 1-显示 0-隐藏
                                'select_list' => $dealEditionFeeTypeList,//可以选择的值
                                'type' => 'select',//类型 select-选择 text-文字
                            ],
                            [
                                'tips' => '版费',//字段文字提示
                                'filed_name' => 'edition_fee',//字段名称
                                'default_value' => $customerOrderPriceRow['edition_fee'],//默认值（展示的值）
                                'is_edit' => 1,//是否可编辑，1-允许 0-禁止
                                'placeholder' => '请输入版费',//占位提示字符
                                'is_change' => (\App\Eloquent\Ygt\CustomerOrderDealUpdateLog::where(['customer_order_id' => $customerOrderId, 'deal_field_name' => 'edition_fee'])->first()) ? 1 : 0,//是否有修改
//                                'is_show' => ($customerOrderPriceRow['edition_fee_type'] == 3) ? 0 : 1,//是否显示 1-显示 0-隐藏
                                'is_show' => 1,//是否显示 1-显示 0-隐藏
                                'type' => 'text',//类型 select-选择 text-文字
                            ],
                            [
                                'tips' => '运费',//字段文字提示
                                'filed_name' => 'freight_fee',//字段名称
                                'default_value' => $customerOrderPriceRow['freight_fee'],//默认值（展示的值）
                                'is_edit' => 1,//是否可编辑，1-允许 0-禁止
                                'placeholder' => '请输入运费',//占位提示字符
                                'is_change' => (\App\Eloquent\Ygt\CustomerOrderDealUpdateLog::where(['customer_order_id' => $customerOrderId, 'deal_field_name' => 'freight_fee'])->first()) ? 1 : 0,//是否有修改
                                'is_show' => 1,//是否显示 1-显示 0-隐藏
                                'type' => 'text',//类型 select-选择 text-文字
                            ],
                            [
                                'tips' => '税点',//字段文字提示
                                'filed_name' => 'tax_point',//字段名称
                                'default_value' => $customerOrderPriceRow['tax_point'],//默认值（展示的值）
                                'is_edit' => 1,//是否可编辑，1-允许 0-禁止
                                'placeholder' => '请输入税点',//占位提示字符
                                'is_change' => (\App\Eloquent\Ygt\CustomerOrderDealUpdateLog::where(['customer_order_id' => $customerOrderId, 'deal_field_name' => 'tax_point'])->first()) ? 1 : 0,//是否有修改
                                'is_show' => 1,//是否显示 1-显示 0-隐藏
                                'type' => 'text',//类型 select-选择 text-文字
                            ],
                        ];

                        $showPriceFiled = 1;
                        $editCustomerOrder = 1;
                        $submitButtonList[] = [
                            'button_name' => '提交修改',
                            'deal_type' => 'sellerSubmit',
                            'submit_type' => 'reject',
                        ];
                        $submitButtonList[] = [
                            'button_name' => '签署确认',
                            'deal_type' => 'sellerSubmit',
                            'submit_type' => 'agree',
                            'check_field_data' => '小秘书温馨提示：如果您确认签署此客户订单，那么客户订单详情将不会被修改！',
                        ];

                        $topTips = [
                            'tips' => '请修改/确认订单',
                            'color' => '#FF7E50',
                        ];
                    } else {
                        $customerOrderPirceArr = [
                            'price_tips' => '单价',//订单价格前的文字提示
                            'price' => $customerOrderPriceRow['sale_price'],//订单价格
                            'is_edit' => 2,//是否可编辑
                            'text_color' => '#FF7E50',//字体颜色
                        ];


                        //其他价格填写
                        $otherOrderPriceList = [
                            [
                                'tips' => '版费类型',//字段文字提示
                                'filed_name' => 'edition_fee_type',//字段名称
                                'default_value' => isset($editionFeeTypeList[$customerOrderPriceRow['edition_fee_type']]) ? $editionFeeTypeList[$customerOrderPriceRow['edition_fee_type']] : '',//默认值（展示的值）
                                'default_select_id' => $customerOrderPriceRow['edition_fee_type'] ? $customerOrderPriceRow['edition_fee_type'] : '',//默认ID（展示的值）
                                'is_edit' => 0,//是否可编辑，1-允许 0-禁止
                                'placeholder' => '请输入版费类型',//占位提示字符
                                'is_change' => 0,//是否有修改
                                'is_show' => 0,//是否显示 1-显示 0-隐藏
                                'select_list' => $dealEditionFeeTypeList,//可以选择的值
                                'type' => 'select',//类型 select-选择 text-文字
                            ],
                            [
                                'tips' => '版费',//字段文字提示
                                'filed_name' => 'edition_fee',//字段名称
                                'default_value' => $customerOrderPriceRow['edition_fee'],//默认值（展示的值）
                                'is_edit' => 0,//是否可编辑，1-允许 0-禁止
                                'placeholder' => '请输入版费',//占位提示字符
                                'is_change' => (\App\Eloquent\Ygt\CustomerOrderDealUpdateLog::where(['customer_order_id' => $customerOrderId, 'deal_field_name' => 'edition_fee'])->first()) ? 1 : 0,//是否有修改
//                                'is_show' => ($customerOrderPriceRow['edition_fee_type'] == 3) ? 0 : 1,//是否显示 1-显示 0-隐藏
                                'is_show' => 1,//是否显示 1-显示 0-隐藏
                                'type' => 'text',//类型 select-选择 text-文字
                            ],
                            [
                                'tips' => '运费',//字段文字提示
                                'filed_name' => 'freight_fee',//字段名称
                                'default_value' => $customerOrderPriceRow['freight_fee'],//默认值（展示的值）
                                'is_edit' => 0,//是否可编辑，1-允许 0-禁止
                                'placeholder' => '请输入运费',//占位提示字符
                                'is_change' => (\App\Eloquent\Ygt\CustomerOrderDealUpdateLog::where(['customer_order_id' => $customerOrderId, 'deal_field_name' => 'freight_fee'])->first()) ? 1 : 0,//是否有修改
                                'is_show' => 1,//是否显示 1-显示 0-隐藏
                                'type' => 'text',//类型 select-选择 text-文字
                            ],
                            [
                                'tips' => '税点',//字段文字提示
                                'filed_name' => 'tax_point',//字段名称
                                'default_value' => $customerOrderPriceRow['tax_point'],//默认值（展示的值）
                                'is_edit' => 0,//是否可编辑，1-允许 0-禁止
                                'placeholder' => '请输入税点',//占位提示字符
                                'is_change' => (\App\Eloquent\Ygt\CustomerOrderDealUpdateLog::where(['customer_order_id' => $customerOrderId, 'deal_field_name' => 'tax_point'])->first()) ? 1 : 0,//是否有修改
                                'is_show' => 1,//是否显示 1-显示 0-隐藏
                                'type' => 'text',//类型 select-选择 text-文字
                            ],
                        ];

                        $showPriceFiled = 1;
                    }

                    break;
                case '100':
                    ////订单已确认
                    $customerOrderPirceArr = [
                        'price_tips' => '单价',//订单价格前的文字提示
                        'price' => $customerOrderPriceRow['deal_price'],//订单价格
                        'is_edit' => 2,//是否可编辑
                        'text_color' => '#000000',//字体颜色
                    ];


                    //其他价格填写
                    $otherOrderPriceList = [
                        [
                            'tips' => '版费类型',//字段文字提示
                            'filed_name' => 'edition_fee_type',//字段名称
                            'default_value' => isset($editionFeeTypeList[$customerOrderPriceRow['edition_fee_type']]) ? $editionFeeTypeList[$customerOrderPriceRow['edition_fee_type']] : '',//默认值（展示的值）
                            'default_select_id' => $customerOrderPriceRow['edition_fee_type'] ? $customerOrderPriceRow['edition_fee_type'] : '',//默认ID（展示的值）
                            'is_edit' => 1,//是否可编辑，1-允许 0-禁止
                            'placeholder' => '请输入版费类型',//占位提示字符
                            'is_change' => 0,//是否有修改
                            'is_show' => 0,//是否显示 1-显示 0-隐藏
                            'select_list' => $dealEditionFeeTypeList,//可以选择的值
                            'type' => 'select',//类型 select-选择 text-文字
                        ],
                        [
                            'tips' => '版费',//字段文字提示
                            'filed_name' => 'edition_fee',//字段名称
                            'default_value' => $customerOrderPriceRow['edition_fee'],//默认值（展示的值）
                            'is_edit' => 1,//是否可编辑，1-允许 0-禁止
                            'placeholder' => '请输入版费',//占位提示字符
                            'is_change' => (\App\Eloquent\Ygt\CustomerOrderDealUpdateLog::where(['customer_order_id' => $customerOrderId, 'deal_field_name' => 'edition_fee'])->first()) ? 1 : 0,//是否有修改
//                            'is_show' => ($customerOrderPriceRow['edition_fee_type'] && $customerOrderPriceRow['edition_fee_type'] != 3) ? 1 : 0,//是否显示 1-显示 0-隐藏
                            'is_show' => 1,//是否显示 1-显示 0-隐藏
                            'type' => 'text',//类型 select-选择 text-文字
                        ],
                        [
                            'tips' => '运费',//字段文字提示
                            'filed_name' => 'freight_fee',//字段名称
                            'default_value' => $customerOrderPriceRow['freight_fee'],//默认值（展示的值）
                            'is_edit' => 0,//是否可编辑，1-允许 0-禁止
                            'placeholder' => '请输入运费',//占位提示字符
                            'is_change' => (\App\Eloquent\Ygt\CustomerOrderDealUpdateLog::where(['customer_order_id' => $customerOrderId, 'deal_field_name' => 'freight_fee'])->first()) ? 1 : 0,//是否有修改
                            'is_show' => 1,//是否显示 1-显示 0-隐藏
                            'type' => 'text',//类型 select-选择 text-文字
                        ],
                        [
                            'tips' => '税点',//字段文字提示
                            'filed_name' => 'tax_point',//字段名称
                            'default_value' => $customerOrderPriceRow['tax_point'],//默认值（展示的值）
                            'is_edit' => 0,//是否可编辑，1-允许 0-禁止
                            'placeholder' => '请输入税点',//占位提示字符
                            'is_change' => (\App\Eloquent\Ygt\CustomerOrderDealUpdateLog::where(['customer_order_id' => $customerOrderId, 'deal_field_name' => 'tax_point'])->first()) ? 1 : 0,//是否有修改
                            'is_show' => 1,//是否显示 1-显示 0-隐藏
                            'type' => 'text',//类型 select-选择 text-文字
                        ],
                    ];

                    $showPriceFiled = 1;
                    $editCustomerOrder = 0;

                    $topTips = [
                        'tips' => '客户已确认订单',
                        'color' => '#04C9B3',
                    ];

                    break;
                default :
                    break;
            }
        }


        //订单详情信息
        /****订单创建详情页-基础信息****/
        //订单基础信息字段，目前格式固定
        //用户id&企业id
        $orderEngine = new OrderEngine();
        $orderBaseFieldList = $orderEngine->orderBaseFieldList($companyId);

        //添加默认值
        $allDataList = [];//包含订单基础信息和工序信息
        $curOrderRow = $customerOrderRow;

        $baseHasChange = 0;
        if (!empty($curOrderRow)) {
            foreach ($orderBaseFieldList as $key => $row) {
                $orderBaseFieldList[$key]['deal_field_name'] = 'base___' . $orderBaseFieldList[$key]['field_name'];
                if ($showChagedData) {
                    if (\App\Eloquent\Ygt\CustomerOrderDealUpdateLog::where(['customer_order_id' => $customerOrderId, 'deal_field_name' => $orderBaseFieldList[$key]['deal_field_name']])->first()) {
                        //如果有修改
                        $orderBaseFieldList[$key]['is_change'] = 1;
                        $baseHasChange = 1;
                    } else {
                        $orderBaseFieldList[$key]['is_change'] = 0;
                    }
                }

                if ($editCustomerOrder) {
                    $orderBaseFieldList[$key]['is_able_edit'] = 1;
                } else {
                    $orderBaseFieldList[$key]['is_able_edit'] = 0;
                    $orderBaseFieldList[$key]['placeholder'] = '';
                }


                if (isset($curOrderRow[$row['field_name']]) && $curOrderRow[$row['field_name']]) {

                    if ($row['field_type'] == 5) {//填写+单位选择 处理
                        $oldRow = $curOrderRow[$row['field_name']];
                        $oldRowArr = explode(',', $oldRow);
                        if (count($oldRowArr) > 1) {
                            $defaultValue = $oldRowArr[0];
                            $oldUnitTitle = $oldRowArr[1];
                            $oldUnitId = $this->getUnitIdByTitle($oldUnitTitle, $row['field_unit']);
                            if (!$oldUnitId) {
                                if (count($row['field_unit'])) {
                                    $oldUnitId = $row['field_unit'][0]['id'];
                                    $oldUnitTitle = $row['field_unit'][0]['title'];
                                } else {
                                    $oldUnitId = 0;
                                    $oldUnitTitle = '';
                                }
                            }

                            $orderBaseFieldList[$key]['default_value'] = $defaultValue;
                            $orderBaseFieldList[$key]['default_unit_id'] = $oldUnitId;
                            $orderBaseFieldList[$key]['default_unit_title'] = $oldUnitTitle;
                        }
                    } elseif ($row['field_type'] == 8) {//配送地址 处理
                        $customerAddressId = $curOrderRow[$row['field_name']];

//                        $customerAddressRow = CustomerAddress::where(['id' => $customerAddressId])->first();
                        $addressWhere = ['id' => $customerAddressId];
                        $customerAddress = \App\Eloquent\Ygt\BuyersAddress::withTrashed()->where($addressWhere)->first();
                        $customerAddressRow = [];
                        if ($customerAddress) {
                            $customerAddressRow = $customerAddress->toArray();
                            $showTitle = $customerAddressRow['province_name'] . $customerAddressRow['city_name'] . $customerAddressRow['area_name'];
                        }


                        $orderBaseFieldList[$key]['default_select_id'] = $customerAddressId;
                        $orderBaseFieldList[$key]['default_value'] = $showTitle;

                    } elseif ($row['field_type'] == 9) {//图片处理
                        $oldImgRow = $curOrderRow[$row['field_name']];
                        $imgIdList = explode(',', $oldImgRow);

                        $imgUrlListStr = '';
                        foreach ($imgIdList as $imgId) {
                            if (!trim($imgId)) {//过滤空格 图片id应该不会有0
                                continue;
                            }
                            $imgUrl = ImgUpload::getImgUrlById($imgId);
                            $imgUrlListStr .= $imgUrl . ',';
                        }

                        $imgUrlListStr = trim($imgUrlListStr, ',');
                        $orderBaseFieldList[$key]['default_img_id'] = $oldImgRow;
                        $orderBaseFieldList[$key]['default_img_url'] = $imgUrlListStr;
                    } elseif ($row['field_type'] == 17) {//版 处理
//                        $selectId = $curOrderRow[$row['field_name']];
//                        $orderBaseFieldList[$key]['default_select_id'] = $selectId;
//                        $plateRow = PlateEngine::getPlateInfo($selectId);
//
//                        if ($plateRow) {
////                            $tmpObj = \App\Eloquent\Ygt\BuyersProduct::where(['id'=>$plateRow['plate_name']])->first();
////                            if($tmpObj){
////                                $showTitle = $tmpObj['name'];
////                            }else{
////                                $showTitle = $plateRow['plate_name'];
////                            }
//                            $showTitle = $plateRow['plate_no'];
//                        } else {
//                            $showTitle = $curOrderRow[$row['field_name']];
//                        }
//
//                        $orderBaseFieldList[$key]['default_value'] = $showTitle;

                        //新的版数据
                        $tmpCreateOrderPlateRow = \App\Eloquent\Ygt\CreateOrderPlate::where(['id'=>$curOrderRow[$row['field_name']]])->first();
                        $plateInfo = json_decode(htmlspecialchars_decode($tmpCreateOrderPlateRow['content']), true);;
                        if(empty($plateInfo)){
                            $plateInfo = null;
                        }

                        $orderBaseFieldList[$key]['default_value'] = '';
                        $orderBaseFieldList[$key]['default_plate_list'] = $plateInfo;


                    } elseif ($row['field_type'] == 18) {//客户 处理
                        $selectId = $curOrderRow[$row['field_name']];
                        $orderBaseFieldList[$key]['default_select_id'] = $selectId;

                        $customerTitle = CustomerEngine::getNameById($selectId);
                        if ($customerTitle) {
                            $showTitle = $customerTitle;
                        } else {
                            $showTitle = $curOrderRow[$row['field_name']];
                        }
                        $orderBaseFieldList[$key]['default_value'] = $showTitle;

                        //客户都不能再修改
                        $orderBaseFieldList[$key]['is_able_edit'] = 0;
                    } elseif ($row['field_type'] == 19) {//单位 处理
                        $selectId = $curOrderRow[$row['field_name']];
                        $orderBaseFieldList[$key]['default_select_id'] = $selectId;

                        $buyersTitle = Buyers::getNameById($selectId);

                        if ($buyersTitle) {
                            $showTitle = $buyersTitle;
                        } else {
                            $showTitle = $curOrderRow[$row['field_name']];
                        }
                        $orderBaseFieldList[$key]['default_value'] = $showTitle;

                        //如果是客户创建的订单，下单人或销售员不能修改单位、品名
                        if ($customerUserId == $customerOrderRow['uid']) {
                            if ($userId != $customerOrderRow['uid']) {
                                $orderBaseFieldList[$key]['is_able_edit'] = 0;
                            }
                        }


                    } elseif ($row['field_type'] == 20) {//品名 处理
                        $selectId = $curOrderRow[$row['field_name']];
                        $orderBaseFieldList[$key]['default_select_id'] = $selectId;

                        $buyersProduct = \App\Eloquent\Ygt\BuyersProduct::where(['id' => $selectId])->first();

                        if ($buyersProduct) {
                            $showTitle = $buyersProduct['name'];
                        } else {
                            $showTitle = $curOrderRow[$row['field_name']];
                        }
                        $orderBaseFieldList[$key]['default_value'] = $showTitle;

                        //如果是客户创建的订单，下单人或销售员不能修改单位、品名
                        if ($customerUserId == $customerOrderRow['uid']) {
                            if ($userId != $customerOrderRow['uid']) {
                                $orderBaseFieldList[$key]['is_able_edit'] = 0;
                            }
                        }


                    } elseif ($row['field_type'] == 21) {//开票资料 处理
                        $selectId = $curOrderRow[$row['field_name']];
                        $orderBaseFieldList[$key]['default_select_id'] = $selectId;

                        $buyersInvoice = \App\Eloquent\Ygt\BuyersInvoice::where(['id' => $selectId])->first();

                        if ($buyersInvoice) {
                            $showTitle = $buyersInvoice['account_name'];
                        } else {
                            $showTitle = $curOrderRow[$row['field_name']];
                        }
                        $orderBaseFieldList[$key]['default_value'] = $showTitle;
                    }elseif ($row['field_type'] == 22) {//半成品展示


                        $tmpCreateOrderProcessProductRow = \App\Eloquent\Ygt\CreateOrderProcessProduct::where(['id'=>$curOrderRow[$row['field_name']]])->first();
                        $processProductInfo = json_decode(htmlspecialchars_decode($tmpCreateOrderProcessProductRow['content']), true);
                        if(empty($processProductInfo)){
                            $processProductInfo = null;
                        }

                        $orderBaseFieldList[$key]['default_value'] = '';
                        $orderBaseFieldList[$key]['default_process_product_list'] = $processProductInfo;


                    }

                    else {
                        $orderBaseFieldList[$key]['default_value'] = $curOrderRow[$row['field_name']];
                    }
                }
            }

            $allDataList[] = [
                'title' => $baseHasChange ? '基础信息【有新的修改】' : '基础信息',
                'field_list' => $orderBaseFieldList,
            ];

        }

        /****工单创建详情页-工单信息****/
        $processList = [];
        //第一个工序
        $orderTypeObj = new \App\Engine\OrderType();
        $firstProcessId = $orderTypeObj->getFirstOneProcessId($curOrderRow['order_type']);
        $curProcessId = $firstProcessId;

        while ($curProcessId) {
            //通过工序id，获取对应的字段
            $processFieldList = Process::getFieldListByProcessId($curProcessId);
            //获取工序信息
            $processTitle = Process::getOneValueById($curProcessId, 'title');

            $tmpProcessHasChange = 0;

            $curOrderProcessRow = [];
            if ($curOrderRow['id']) {//如果传入复制工单id
                $curOrderProcessRow = \App\Eloquent\Ygt\CustomerOrderProcess::where(['order_id' => $curOrderRow['id'], 'process_type' => $curProcessId])->first();
                if (!empty($curOrderProcessRow)) {
                    $curOrderProcessRow = $curOrderProcessRow->toArray();
                }
            }

            //添加默认值
            foreach ($processFieldList as $key => $row) {
                $processFieldList[$key]['deal_field_name'] = $curOrderProcessRow['id'] . '___' . $processFieldList[$key]['field_name'];
                $processFieldList[$key]['process_id'] = $curOrderProcessRow['process_type'];

                if ($editCustomerOrder) {
                    $processFieldList[$key]['is_able_edit'] = 1;
                } else {
                    $processFieldList[$key]['is_able_edit'] = 0;
                }

                if ($showChagedData) {
                    if (\App\Eloquent\Ygt\CustomerOrderDealUpdateLog::where(['customer_order_id' => $customerOrderId, 'deal_field_name' => $processFieldList[$key]['deal_field_name']])->first()) {
                        //如果有修改
                        $processFieldList[$key]['is_change'] = 1;
                        $tmpProcessHasChange = 1;
                    } else {
                        $processFieldList[$key]['is_change'] = 0;
                        $processFieldList[$key]['placeholder'] = '';
                    }
                }

                if (isset($curOrderProcessRow[$row['field_name']]) && $curOrderProcessRow[$row['field_name']]) {
                    if ($row['field_type'] == 3) {//选择 处理
                        $selectId = $this->getSidByTitle($curOrderProcessRow[$row['field_name']], $row['data']);
                        $processFieldList[$key]['default_select_id'] = $selectId;
                        $processFieldList[$key]['default_value'] = $curOrderProcessRow[$row['field_name']];
                    } elseif ($row['field_type'] == 5) {//填写+单位选择 处理
                        $oldRow = $curOrderProcessRow[$row['field_name']];
                        $oldRowArr = explode(',', $oldRow);
                        if (count($oldRowArr) > 1) {//异常数据处理
                            $defaultValue = $oldRowArr[0];
                            $oldUnitTitle = $oldRowArr[1];
                            $oldUnitId = $this->getUnitIdByTitle($oldUnitTitle, $row['field_unit']);
                            if (!$oldUnitId) {
                                if (count($row['field_unit'])) {
                                    $oldUnitId = $row['field_unit'][0]['id'];
                                    $oldUnitTitle = $row['field_unit'][0]['title'];
                                } else {
                                    $oldUnitId = 0;
                                    $oldUnitTitle = '';
                                }
                            }

                            $processFieldList[$key]['default_value'] = $defaultValue;
                            $processFieldList[$key]['default_unit_id'] = $oldUnitId;
                            $processFieldList[$key]['default_unit_title'] = $oldUnitTitle;
                        }
                    } elseif ($row['field_type'] == 4) {//选择材料页面
                        $materialIdListStr = $curOrderProcessRow[$row['field_name']];
                        $materialIdList = explode(',', $materialIdListStr);

                        //获取优选采购的材料id
                        $recommendMaterialIdArr = OrderMaterialPurchaseMark::where('customer_order_id','=',$customerOrderId)
                            ->where('is_purchase','=',1)->pluck('material_id')->toArray();
                        $materialList = [];
                        foreach ($materialIdList as $materialId) {
                            //考虑集合材料的问题
                            if(strstr($materialId,'A')){
                                $tmpAssemblageMaterialId = str_replace('A','',$materialId);
                                $materialRow = \App\Eloquent\Ygt\AssemblageMaterial::withTrashed()->where(['id'=>$tmpAssemblageMaterialId])->first();

                            }else{
                                $materialRow = ProductEngine::getProductInfo($materialId);
                            }

                            if ($materialRow) {//过滤异常情况 zq
                                //增加材料图片地址 20180719 zhuyujun
                                //追加材料图片地址
                                $materialRow['img_url'] = '';
                                if ($materialRow['img_id']) {
                                    $materialRow['img_url'] = \App\Eloquent\Ygt\ImgUpload::getImgUrlById($materialRow['img_id']);
                                }

                                $materialRow->toArray();

                                if(in_array($materialId,$recommendMaterialIdArr)){
                                    $materialRow['is_purchase'] = 1;
                                }
                                else{
                                    $materialRow['is_purchase'] = 0;
                                }

                                $materialList[] = [
                                    'id' => $materialId,
                                    'product_no' => $materialRow['product_no'],
                                    'product_name' => $materialRow['product_name'],
                                    'image_path' => $materialRow['img_url'],
                                    'is_purchase'=> $materialRow['is_purchase'],
                                ];
                            }

                        }
                        $processFieldList[$key]['default_product_list'] = $materialList;
                    } elseif ($row['field_type'] == 17) {//版 处理
//                        $selectId = $curOrderProcessRow[$row['field_name']];
//                        $processFieldList[$key]['default_select_id'] = $selectId;
//                        $plateRow = PlateEngine::getPlateInfo($selectId);
//
//                        if ($plateRow) {
////                            $tmpObj = \App\Eloquent\Ygt\BuyersProduct::where(['id'=>$plateRow['plate_name']])->first();
////                            if($tmpObj){
////                                $showTitle = $tmpObj['name'];
////                            }else{
////                                $showTitle = $plateRow['plate_name'];
////                            }
//                            $showTitle = $plateRow['plate_no'];
//                        } else {
//                            $showTitle = $curOrderProcessRow[$row['field_name']];
//                        }
//
//                        $processFieldList[$key]['default_value'] = $showTitle;



                        //新的版数据
                        $tmpCreateOrderPlateRow = \App\Eloquent\Ygt\CreateOrderPlate::where(['id'=>$curOrderProcessRow[$row['field_name']]])->first();
                        $plateInfo = json_decode(htmlspecialchars_decode($tmpCreateOrderPlateRow['content']), true);;

                        if(empty($plateInfo)){
                            $plateInfo = null;
                        }

                        $processFieldList[$key]['default_value'] = '';
                        $processFieldList[$key]['default_plate_list'] = $plateInfo;

                    } elseif ($row['field_type'] == 18) {//客户 处理
                        $selectId = $curOrderProcessRow[$row['field_name']];
                        $processFieldList[$key]['default_select_id'] = $selectId;

                        $customerTitle = CustomerEngine::getNameById($selectId);
                        if ($customerTitle) {
                            $showTitle = $customerTitle;
                        } else {
                            $showTitle = $curOrderProcessRow[$row['field_name']];
                        }
                        $processFieldList[$key]['default_value'] = $showTitle;
                    } elseif ($row['field_type'] == 19) {//单位展示
                        $baseId = $curOrderProcessRow[$row['field_name']];
                        $showTitle = Buyers::getNameById($baseId);
                        if (!$showTitle) {
                            $showTitle = $curOrderProcessRow[$row['field_name']];
                        }
                        $processFieldList[$key]['default_value'] = $showTitle;
                    }elseif ($row['field_type'] == 22) {//半成品展示


                        $tmpCreateOrderProcessProductRow = \App\Eloquent\Ygt\CreateOrderProcessProduct::where(['id'=>$curOrderProcessRow[$row['field_name']]])->first();
                        $processProductInfo = json_decode(htmlspecialchars_decode($tmpCreateOrderProcessProductRow['content']), true);
                        if(empty($processProductInfo)){
                            $processProductInfo = null;
                        }

                        $processFieldList[$key]['default_value'] = '';
                        $processFieldList[$key]['default_process_product_list'] = $processProductInfo;


                    }

                    else {
                        $processFieldList[$key]['default_value'] = $curOrderProcessRow[$row['field_name']];
                    }
                }
            }

            $curProcess = [
//                'process_id' => $curProcessId,
                'title' => $tmpProcessHasChange ? $processTitle . '【有新的修改】' : $processTitle,
                'field_list' => $processFieldList,
            ];
            $allDataList[] = $curProcess;
            //下一个工序
            $curProcessId = $orderTypeObj->getNextOneProcessId($curOrderRow['order_type'], $curProcessId);//获取下一个工序
        }

        //客商转交订单给销售员后，保存一次数据到备份库，用于给客商查看（不然客商看到最新的订单情况）
        if ($customerOrderPriceRow['status'] == 1) {//销售员进入页面时保存数据
            $tmpObj = \App\Eloquent\Ygt\CustomerOrderBakforcustomer::firstOrNew(['customer_order_id' => $customerOrderPriceRow['customer_order_id']]);
            $tmpObj->customer_order_id = $customerOrderPriceRow['customer_order_id'];
            $tmpObj->content = \GuzzleHttp\json_encode($allDataList);
            $tmpObj->save();
        }

        if ($customerOrderPriceRow['status'] == 2 || $customerOrderPriceRow['status'] == 3) {
            //如果是客商,在此阶段，看到的订单信息从备份信息中获取
            if ($userInfo['company_id'] == 2) {
                $tmpObj = \App\Eloquent\Ygt\CustomerOrderBakforcustomer::where(['customer_order_id' => $customerOrderPriceRow['customer_order_id']])->first();
                if ($tmpObj) {
                    $allDataList = \GuzzleHttp\json_decode($tmpObj->content);
                }
            }
        }

        /**一直存在的按钮**/
        //下单人可以直接转工单 && 报价给销售
        $privilegeIdList = \App\Engine\OrderEngine::getPrivilegeByNode($companyId, 1);
        if (in_array($userInfo['privilege_id'], $privilegeIdList)) {
            $submitButtonList[] = [
                'button_name' => '创建工单',
                'deal_type' => 'customerOrderToOrder',
            ];

            $customerOrderPirceArr['is_edit'] = 1;//下单人始终允许填写成本价


            if(!$customerOrderPriceRow['singleperson_price']){
                //如果同时为下单人和销售员,成本价==销售价
                $privilegeIdList2 = \App\Engine\OrderEngine::getPrivilegeByNode($companyId, 13);
                if (in_array($userInfo['privilege_id'], $privilegeIdList2)) {
                    $customerOrderPriceRow['singleperson_price'] = $customerOrderPriceRow['sale_price'];
                }
            }

            $customerOrderPirceArr['price'] = $customerOrderPriceRow['singleperson_price'];//下单人显示自己填的成本价

            //如果同时是销售员，不显示报成本价
            $privilegeIdList2 = \App\Engine\OrderEngine::getPrivilegeByNode($companyId, 13);
            if (!in_array($userInfo['privilege_id'], $privilegeIdList2) || (isset($customerOrderPriceRow['status']) && $customerOrderPriceRow['status'] == 2)) {
                $submitButtonList[] = [
                    'button_name' => '报成本价',
                    'deal_type' => 'singlepersonSubmitPrices',
                    'check_field_data' => '小秘书温馨提示：您确认成本价计算准确吗？',
                ];
            }
        }

        //销售员可以提醒下单人下单&转交下单人报价
        $privilegeIdList = \App\Engine\OrderEngine::getPrivilegeByNode($companyId, 13);
        //如果同时是下单人，不显示按钮 -- 主要是放不下
        if (in_array($userInfo['privilege_id'], $privilegeIdList)) {
            $privilegeIdList2 = \App\Engine\OrderEngine::getPrivilegeByNode($companyId, 1);
            if (!in_array($userInfo['privilege_id'], $privilegeIdList2)){
                $submitButtonList[] = [
                    'button_name' => '核单',
                    'deal_type' => 'transferToSingleperson',
                    'is_refresh' => 1,
                ];
                $submitButtonList[] = [
                    'button_name' => '下工单',
                    'deal_type' => 'alterSinglepersonOrder',
                    'is_refresh' => 1,
                ];
            }
        }





        return [
            'customer_order_price_arr' => $customerOrderPirceArr,//订单价格相关数据
            'other_order_price_list' => $otherOrderPriceList,//其他价格相关数据
            'show_price_filed' => $showPriceFiled,//是否显示订单价格按钮 0-隐藏 1-显示
            'submit_button_list' => $submitButtonList,//页面上展示的按钮
            'top_tips' => $topTips,//头部提示文字
            'data_list' => $allDataList,
        ];
    }

    //获得工单相应消息内容
    private function getCustomerOrderRelateMessageContent($customerOrderId,$fields,$customerOrderRow = []){
        if(empty($customerOrderRow)){
            $customerOrderRow = \App\Eloquent\Ygt\CustomerOrder::where(['id' => $customerOrderId])->first();
        }

        $messageContent = '';
        foreach($fields as $key=>$val){
            if(!empty($val)){
                $messageContent .= 'rnrn'.$key.':'.$val;
            }
            else{
                switch($key) {
                    case '单位名称':
                        $value        = \App\Engine\OrderEngine::getOrderFiledValueTrue($customerOrderRow['field_name_23'], 19);//单位名称
                        $messageContent .= 'rnrn'.$key.':'.$value;
                        break;
                    case '工序名称':
                        $value        = \App\Engine\OrderType::getOneValueById($customerOrderRow['order_type'], 'title');//工序名称
                        $messageContent .= 'rnrn'.$key.':'.$value;
                        break;
                    case '品名':
                        $value          = \App\Engine\OrderEngine::getOrderFiledValueTrue($customerOrderRow['product_name'], 20);//品名
                        $messageContent .= 'rnrn'.$key.':'.$value;
                        break;
                    case '成品规格':
                        $value        = \App\Engine\OrderEngine::getOrderFiledValueTrue($customerOrderRow['finished_specification'], 16);//片料规格
                        $messageContent .= 'rnrn'.$key.':'.$value;
                        break;
                    case '数量':
                        $value          = \App\Engine\OrderEngine::getOrderFiledValueTrue($customerOrderRow['product_num'], 5);//数量
                        $messageContent .= 'rnrn'.$key.':'.$value;
                        break;
                    case '交货日期':
                        $value        = $customerOrderRow['finished_date'];
                        $messageContent .= 'rnrn'.$key.':'.$value;
                        break;
                    case '订单号':
                        $value        = $customerOrderRow['order_title'];
                        $messageContent .= 'rnrn'.$key.':'.$value;
                        break;
                    case '客户名称':
                        $value        = Customer::getOneValueById($customerOrderRow['customer_name'],'customer_name');
                        $messageContent .= 'rnrn'.$key.':'.$value;
                    default :
                        break;
                }
            }
        }

        return $messageContent;
    }


    //提交价格（意见）
    public function customerOrderPriceDeal()
    {
        $userId = Func::getHeaderValueByName('userid',25);
        $userInfo = DepartmentUser::getCurrentInfo($userId)->toArray();

        $customerOrderId = request('customer_order_id');
        $price = request('price');//提交的订单价格
        $editionFeeType = request('edition_fee_type');//提交的版费类型
        $editionFee = request('edition_fee');//提交的版费
        $freightFee = request('freight_fee');//提交的运费
        $taxPoint = request('tax_point');//提交的税点

        if (!$editionFee && $editionFee !== '0') {
            $editionFee = null;
        }
        if (!$freightFee && $freightFee !== '0') {
            $freightFee = null;
        }
        if (!$taxPoint && $taxPoint !== '0') {
            $taxPoint = null;
        }

        $submitType = request('submit_type');//提交的状态

        $customerOrderRow = \App\Eloquent\Ygt\CustomerOrder::where(['id' => $customerOrderId])->first();
        $companyId = $customerOrderRow['company_id'];


        $dealType = request('deal_type');
        //transferToSingleperson -- 转交给下单人
        //singlepersonSubmitPrices -- 下单人提交价格
        //transferToCustomer -- 转交给客户
        //customerSubmit -- 客户提交
        //sellerSubmit -- 销售员提交
        //directConfirmPrice - 直接确认订单价格
        switch ($dealType) {
            case 'alterSinglepersonOrder': //提醒下单人下单
                //发送消息
                //获取下单人权限的角色
                $privilegeIdList = \App\Engine\OrderEngine::getPrivilegeByNode($companyId, 1);
                foreach ($privilegeIdList as $privilegeId) {
                    if ($privilegeId) {
                        $data = [
                            'company_id' => $companyId,
                            'privilege_id' => $privilegeId,
                            'form_user_id' => $userId,
                            'to_user_id' => '',
                            'foreign_key' => $customerOrderId,
                            'type' => 19,//type待定
                            'type_id' => $customerOrderId,
                            'title' => $customerOrderRow['order_title'],
                            'content' => '请尽快下工单',
                            'theme'=>'提醒下工单'
                        ];
                        UserMessage::sendCustomerOrderMessage($data);
                    }
                }

                break;
            case 'transferToSingleperson': //transferToSingleperson -- 转交给下单人
                //如果订单状态不为1，只发送消息给下单人，不修改状态和订单详情
                $customerOrderPriceObj = \App\Eloquent\Ygt\CustomerOrderPrice::firstOrNew(['customer_order_id' => $customerOrderId]);

                if($customerOrderPriceObj['status'] == 1){
                    //修改订单数据
                    $messageContent = $this->updateCustomerOrderInfo($customerOrderId, $userId);

                    //修改状态
                    $tmpInsterRow = [
                        'customer_order_id' => $customerOrderId,
                        'sale_uid' => $userId,
                        'status' => 2,//状态2 下单人定价格
                    ];
                    $customerOrderPriceObj->fill($tmpInsterRow);
                    $customerOrderPriceObj->save();
                }


                //消息内容
                $messageContent = $this->getCustomerOrderRelateMessageContent(
                    $customerOrderId,
                    [
                        '工艺名称'=>'',
                        '客户名称'=>'',
                        '单位名称'=>'',
                        '品名'=>'',
                        '成品规格'=>'',
                        '数量'=>'',
                        '交货日期'=>'',
                        '订单号'=>'',
                    ],
                    $customerOrderRow
                );

                //发送消息
                //获取下单人权限的角色
                $privilegeIdList = \App\Engine\OrderEngine::getPrivilegeByNode($companyId, 1);
                foreach ($privilegeIdList as $privilegeId) {
                    if ($privilegeId) {
                        $data = [
                            'company_id' => $companyId,
                            'privilege_id' => $privilegeId,
                            'form_user_id' => $userId,
                            'to_user_id' => '',
                            'foreign_key' => $customerOrderId,
                            'type' => 19,//type待定
                            'type_id' => $customerOrderId,
                            'title' => $customerOrderRow['order_title'],
                            'content' => $messageContent,
                            'theme'=>'订单询价'
                        ];
                        UserMessage::sendCustomerOrderMessage($data);
                    }
                }

                break;

            case 'directPrice': //directPrice -- 直接报价格客户
                //修改状态
                $customerOrderPriceObj = \App\Eloquent\Ygt\CustomerOrderPrice::firstOrNew(['customer_order_id' => $customerOrderId]);
                $tmpInsterRow = [
                    'customer_order_id' => $customerOrderId,
                    'sale_uid' => $userId,
                    'status' => 3,//状态3 直接报价格客户
                ];
                $customerOrderPriceObj->fill($tmpInsterRow);
                $customerOrderPriceObj->save();

                break;
                
            case 'singlepersonSubmitPrices':  //singlepersonSubmitPrices -- 下单人提交价格
                if (!$price) {
                    return [
                        'code' => 1,
                        'message' => '请填写价格'
                    ];
                }

                $isSeller = 0;//是否同时为销售
                $privilegeIdList2 = \App\Engine\OrderEngine::getPrivilegeByNode($companyId, 13);
                if (in_array($userInfo['privilege_id'], $privilegeIdList2)) {
                    $isSeller = 1;
                }

                //下单人报价如果是在销售报价客户之后，只发消息，不对订单进行修改（成本价可以继续调整）只有订单状态为2时，可以修改订单
                //zhuyujun 20181225
                if($customerOrderRow['status'] != 2 && !$isSeller){
                    /**只发消息&修改成本价**/
                    //提交价格
                    $customerOrderPriceObj = \App\Eloquent\Ygt\CustomerOrderPrice::firstOrNew(['customer_order_id' => $customerOrderId]);
                    $tmpInsterRow = [
                        'singleperson_price' => $price,
                    ];
                    $customerOrderPriceObj->fill($tmpInsterRow);
                    $customerOrderPriceObj->save();


                    //消息内容
                    $messageContent = $this->getCustomerOrderRelateMessageContent(
                        $customerOrderId,
                        [
                            '工艺名称'=>'',
                            '客户名称'=>'',
                            '单位名称'=>'',
                            '品名'=>'',
                            '成品规格'=>'',
                            '数量'=>'',
                            '交货日期'=>'',
                            '成本单价'=>$price,
                            '订单号'=>'',
                        ],
                        $customerOrderRow
                    );

                    //发送消息给销售员
                    $data = [
                        'company_id' => $companyId,
                        'privilege_id' => '',
                        'form_user_id' => $userId,
                        'to_user_id' => $customerOrderPriceObj['sale_uid'],
                        'foreign_key' => $customerOrderId,
                        'type' => 19,//type待定
                        'type_id' => $customerOrderId,
                        'title' => $customerOrderRow['order_title'],
                        'content' => $messageContent,
                        'theme'=>'订单已核算成本价'
                    ];
                    UserMessage::sendCustomerOrderMessage($data);
                }else{
                    /**正常流程**/
                    //修改订单数据
                    $messageContent = $this->updateCustomerOrderInfo($customerOrderId, $userId);

                    //提交价格
                    $customerOrderPriceObj = \App\Eloquent\Ygt\CustomerOrderPrice::firstOrNew(['customer_order_id' => $customerOrderId]);
                    $tmpInsterRow = [
                        'customer_order_id' => $customerOrderId,
                        'sale_price' => $price,
//                    'edition_fee_type' => $editionFeeType,
//                    'edition_fee' => $editionFee,
//                    'freight_fee' => $freightFee,
//                    'tax_point' => $taxPoint,
                        'singleperson_uid' => $userId,
                        'status' => 3,//状态3 销售员确定并需要转给客户
                    ];
                    $customerOrderPriceObj->fill($tmpInsterRow);
                    $customerOrderPriceObj->save();

                    //保存价格记录
                    $customerOrderPriceLogObj = \App\Eloquent\Ygt\CustomerOrderPriceLog::firstOrNew(['id' => '']);
                    $tmpInsterRow = [
                        'customer_order_id' => $customerOrderId,
                        'customer_order_price_id' => $customerOrderPriceObj->id,
                        'price' => $price,
                        'uid' => $userId,
                        'type' => 1,//1-下单人报价
                    ];
                    $customerOrderPriceLogObj->fill($tmpInsterRow);
                    $customerOrderPriceLogObj->save();


                    //如果用户同时为销售员，直接到提交价格给
                    $privilegeIdList2 = \App\Engine\OrderEngine::getPrivilegeByNode($companyId, 13);
                    if (in_array($userInfo['privilege_id'], $privilegeIdList2)) {
                        $customerOrderPriceObj = \App\Eloquent\Ygt\CustomerOrderPrice::firstOrNew(['customer_order_id' => $customerOrderId]);
                        $tmpInsterRow = [
                            'customer_order_id' => $customerOrderId,
                            'sale_price' => $price,
                            'edition_fee_type' => $editionFeeType,
                            'edition_fee' => $editionFee,
                            'freight_fee' => $freightFee,
                            'tax_point' => $taxPoint,
                            'status' => 4,//状态3 销售员确定并需要转给客户
                        ];



                        $customerOrderPriceObj->fill($tmpInsterRow);
                        $customerOrderPriceObj->save();

                        //发送消息给客户
                        $customerId = $customerOrderRow['customer_name'];
                        //获取客户的用户ID
                        $toUserId = \App\Eloquent\Ygt\Customer::where(['id' => $customerId])->first()->user_id;

                        $messageContent = $this->getCustomerOrderRelateMessageContent(
                            $customerOrderId,
                            [
                                '工艺名称'=>'',
                                '单位名称'=>'',
                                '品名'=>'',
                                '成品规格'=>'',
                                '数量'=>'',
                                '交货日期'=>'',
                                '单价'=>$price,
                                '订单号'=>'',
                            ],
                            $customerOrderRow
                        );

                        $data = [
                            'company_id' => 2,
                            'privilege_id' => '',
                            'form_user_id' => $userId,
                            'to_user_id' => $toUserId,
                            'foreign_key' => $customerOrderId,
                            'type' => 19,//type待定
                            'type_id' => $customerOrderId,
                            'title' => $customerOrderRow['order_title'],
                            'content' => "rnrn" . $messageContent,
                            'theme'=>'销售员已报价'
                        ];
                        UserMessage::sendCustomerOrderMessage($data);

                    } else {
                        //消息内容
                        $messageContent = $this->getCustomerOrderRelateMessageContent(
                            $customerOrderId,
                            [
                                '工艺名称'=>'',
                                '客户名称'=>'',
                                '单位名称'=>'',
                                '品名'=>'',
                                '成品规格'=>'',
                                '数量'=>'',
                                '交货日期'=>'',
                                '成本单价'=>$price,
                                '订单号'=>'',
                            ],
                            $customerOrderRow
                        );

                        //发送消息给销售员
                        $data = [
                            'company_id' => $companyId,
                            'privilege_id' => '',
                            'form_user_id' => $userId,
                            'to_user_id' => $customerOrderPriceObj['sale_uid'],
                            'foreign_key' => $customerOrderId,
                            'type' => 19,//type待定
                            'type_id' => $customerOrderId,
                            'title' => $customerOrderRow['order_title'],
                            'content' => $messageContent,
                            'theme'=>'订单已核算成本价'
                        ];
                        UserMessage::sendCustomerOrderMessage($data);
                    }
                }

                break;
            case 'transferToCustomer'://transferToCustomer -- 转交给客户
                //修改状态
                //修改订单数据
                $messageContent = $this->updateCustomerOrderInfo($customerOrderId, $userId);

                //提交价格
                $customerOrderPriceObj = \App\Eloquent\Ygt\CustomerOrderPrice::firstOrNew(['customer_order_id' => $customerOrderId]);

                if ($editionFee != $customerOrderPriceObj['edition_fee_type']) {
                    $customerOrderDealUpdateLogObj = \App\Eloquent\Ygt\CustomerOrderDealUpdateLog::firstOrNew(['customer_order_id' => $customerOrderId, 'deal_field_name' => 'edition_fee_type']);
                    $tmpInsterRow = [
                        'customer_order_id' => $customerOrderId,
                        'deal_field_name' => 'edition_fee_type',
                        'old_value' => '',
                        'new_value' => $editionFeeType,
                        'uid' => $userId,
                    ];
                    $customerOrderDealUpdateLogObj->fill($tmpInsterRow);
                    $customerOrderDealUpdateLogObj->save();
                }
                if ($editionFee != $customerOrderPriceObj['edition_fee']) {
                    $customerOrderDealUpdateLogObj = \App\Eloquent\Ygt\CustomerOrderDealUpdateLog::firstOrNew(['customer_order_id' => $customerOrderId, 'deal_field_name' => 'edition_fee']);
                    $tmpInsterRow = [
                        'customer_order_id' => $customerOrderId,
                        'deal_field_name' => 'edition_fee',
                        'old_value' => '',
                        'new_value' => $editionFee,
                        'uid' => $userId,
                    ];
                    $customerOrderDealUpdateLogObj->fill($tmpInsterRow);
                    $customerOrderDealUpdateLogObj->save();
                }
                if ($freightFee != $customerOrderPriceObj['freight_fee']) {
                    $customerOrderDealUpdateLogObj = \App\Eloquent\Ygt\CustomerOrderDealUpdateLog::firstOrNew(['customer_order_id' => $customerOrderId, 'deal_field_name' => 'freight_fee']);
                    $tmpInsterRow = [
                        'customer_order_id' => $customerOrderId,
                        'deal_field_name' => 'freight_fee',
                        'old_value' => '',
                        'new_value' => $freightFee,
                        'uid' => $userId,
                    ];
                    $customerOrderDealUpdateLogObj->fill($tmpInsterRow);
                    $customerOrderDealUpdateLogObj->save();
                }
                if ($taxPoint != $customerOrderPriceObj['tax_point']) {
                    $customerOrderDealUpdateLogObj = \App\Eloquent\Ygt\CustomerOrderDealUpdateLog::firstOrNew(['customer_order_id' => $customerOrderId, 'deal_field_name' => 'tax_point']);
                    $tmpInsterRow = [
                        'customer_order_id' => $customerOrderId,
                        'deal_field_name' => 'tax_point',
                        'old_value' => '',
                        'new_value' => $taxPoint,
                        'uid' => $userId,
                    ];
                    $customerOrderDealUpdateLogObj->fill($tmpInsterRow);
                    $customerOrderDealUpdateLogObj->save();
                }

                


                $tmpInsterRow = [
                    'customer_order_id' => $customerOrderId,
                    'sale_price' => $price,
                    'edition_fee' => $editionFee,
                    'edition_fee_type' => $editionFeeType,
                    'freight_fee' => $freightFee,
                    'tax_point' => $taxPoint,
                    'status' => 4,//状态3 销售员确定并需要转给客户
                ];


                $customerOrderPriceObj->fill($tmpInsterRow);
                $customerOrderPriceObj->save();

                //保存价格记录
                $customerOrderPriceLogObj = \App\Eloquent\Ygt\CustomerOrderPriceLog::firstOrNew(['id' => '']);
                $tmpInsterRow = [
                    'customer_order_id' => $customerOrderId,
                    'customer_order_price_id' => $customerOrderPriceObj->id,
                    'price' => $price,
                    'uid' => $userId,
                    'type' => 2,//2-销售员报价
                ];
                $customerOrderPriceLogObj->fill($tmpInsterRow);
                $customerOrderPriceLogObj->save();


                //发送消息给客户
                $customerId = $customerOrderRow['customer_name'];
                //获取客户的用户ID
                $toUserId = \App\Eloquent\Ygt\Customer::where(['id' => $customerId])->first()->user_id;

                //消息内容
                $messageContent = $this->getCustomerOrderRelateMessageContent(
                    $customerOrderId,
                    [
                        '工艺名称'=>'',
                        '单位名称'=>'',
                        '品名'=>'',
                        '成品规格'=>'',
                        '数量'=>'',
                        '交货日期'=>'',
                        '单价'=>$price,
                        '订单号'=>'',
                    ],
                    $customerOrderRow
                );

                $data = [
                    'company_id' => 2,
                    'privilege_id' => '',
                    'form_user_id' => $userId,
                    'to_user_id' => $toUserId,
                    'foreign_key' => $customerOrderId,
                    'type' => 19,//type待定
                    'type_id' => $customerOrderId,
                    'title' => $customerOrderRow['order_title'],
                    'content' => $messageContent,
                    'theme' => '订单报价'
                ];
                UserMessage::sendCustomerOrderMessage($data);

                break;
            case 'customerSubmit' ://customerSubmit -- 客户提交
                if ($submitType == 'agree') {
                    //删除原来的修改记录
                    \App\Eloquent\Ygt\CustomerOrderDealUpdateLog::where(['customer_order_id' => $customerOrderId])->delete();

                    //修改状态
                    $customerOrderPriceObj = \App\Eloquent\Ygt\CustomerOrderPrice::firstOrNew(['customer_order_id' => $customerOrderId]);
                    $tmpInsterRow = [
                        'customer_price' => $customerOrderPriceObj['sale_price'],//订单价格已确定
                        'deal_price' => $customerOrderPriceObj['sale_price'],//订单价格已确定
                        'status' => 100,//订单价格已确定
                    ];
                    $customerOrderPriceObj->fill($tmpInsterRow);
                    $customerOrderPriceObj->save();

                    //保存价格记录
                    $customerOrderPriceLogObj = \App\Eloquent\Ygt\CustomerOrderPriceLog::firstOrNew(['id' => '']);
                    $tmpInsterRow = [
                        'customer_order_id' => $customerOrderId,
                        'customer_order_price_id' => $customerOrderPriceObj->id,
                        'price' => $price,
                        'uid' => $userId,
                        'type' => 3,//3-客户确认价格
                    ];
                    $customerOrderPriceLogObj->fill($tmpInsterRow);
                    $customerOrderPriceLogObj->save();


                    //修改订单标示
                    $customerOrderObj = \App\Eloquent\Ygt\CustomerOrder::where(['id' => $customerOrderId])->first();
                    $customerOrderObj->is_deal_price = 1;
                    $customerOrderObj->save();

                    //消息内容
                    $messageContent = $this->getCustomerOrderRelateMessageContent(
                        $customerOrderId,
                        [
                            '工艺名称'=>'',
                            '单位名称'=>'',
                            '品名'=>'',
                            '成品规格'=>'',
                            '单价'=>$price,
                            '数量'=>'',
                            '交货日期'=>'',
                            '订单号'=>'',
                        ],
                        $customerOrderRow
                    );

                    //发送消息给销售员
                    $data = [
                        'company_id' => $companyId,
                        'privilege_id' => '',
                        'form_user_id' => $userId,
                        'to_user_id' => $customerOrderPriceObj['sale_uid'],
                        'foreign_key' => $customerOrderId,
                        'type' => 19,//type待定
                        'type_id' => $customerOrderId,
                        'title' => $customerOrderRow['order_title'],
                        'content' => $messageContent,
                        'theme' =>'客户已确认订单'
                    ];
                    UserMessage::sendCustomerOrderMessage($data);

                    //发消息给下单人
                    $messageContent = $this->getCustomerOrderRelateMessageContent(
                        $customerOrderId,
                        [
                            '工艺名称'=>'',
                            '单位名称'=>'',
                            '品名'=>'',
                            '成品规格'=>'',
//                            '单价'=>$price,
                            '数量'=>'',
                            '交货日期'=>'',
                            '订单号'=>'',
                        ],
                        $customerOrderRow
                    );

                    if($customerOrderPriceObj['singleperson_uid']){
                        $data = [
                            'company_id' => $companyId,
                            'privilege_id' => '',
                            'form_user_id' => $userId,
                            'to_user_id' => $customerOrderPriceObj['singleperson_uid'],
                            'foreign_key' => $customerOrderId,
                            'type' => 16,//type待定
                            'type_id' => $customerOrderId,
                            'title' => $customerOrderRow['order_title'],
                            'content' => $messageContent,
                            'theme' =>'客户已确认订单'
                        ];
                        UserMessage::sendCustomerOrderMessage($data);
                    }else{
                        //如果议价过程中未涉及到下单人，给所有有下单权限的人发消息
                        //获取下单权限的用户
                        $privilegeIdList = \App\Engine\OrderEngine::getPrivilegeByNode($companyId, 1);
                        foreach ($privilegeIdList as $privilegeId) {
                            if ($privilegeId) {
                                $data = [
                                    'company_id' => $companyId,
                                    'privilege_id' => $privilegeId,
                                    'form_user_id' => $userId,
                                    'to_user_id' => '',
                                    'foreign_key' => $customerOrderId,
                                    'type' => 16,//type待定
                                    'type_id' => $customerOrderId,
                                    'title' => $customerOrderRow['order_title'],
                                    'content' => $messageContent,
                                    'theme' =>'客户已确认订单'
                                ];
                                UserMessage::sendCustomerOrderMessage($data);
                            }
                        }
                    }


                } else {
                    //删除原来的修改记录
                    \App\Eloquent\Ygt\CustomerOrderDealUpdateLog::where(['customer_order_id' => $customerOrderId])->delete();
                    //修改订单消息
                    $messageContent = $this->updateCustomerOrderInfo($customerOrderId, $userId);

                    //修改状态
                    $customerOrderPriceObj = \App\Eloquent\Ygt\CustomerOrderPrice::firstOrNew(['customer_order_id' => $customerOrderId]);
                    //判断价格、运费、版费、税点是否有修改
                    $priceMessageContent = '';
                    if ($price != $customerOrderPriceObj['sale_price']) {
                        $priceMessageContent .= "价格有修改rnrn";
                    }
//                    if($editionFeeType != $customerOrderPriceObj['edition_fee_type']){
//                        $priceMessageContent.="版费类型有修改rnrn";
//                        $customerOrderDealUpdateLogObj = \App\Eloquent\Ygt\CustomerOrderDealUpdateLog::firstOrNew(['customer_order_id'=>$customerOrderId,'deal_field_name'=>'edition_fee_type']);
//                        $tmpInsterRow = [
//                            'customer_order_id' => $customerOrderId,
//                            'deal_field_name' => 'edition_fee_type',
//                            'old_value' => '',
//                            'new_value' => $editionFeeType,
//                            'uid' => $userId,
//                        ];
//                        $customerOrderDealUpdateLogObj->fill($tmpInsterRow);
//                        $customerOrderDealUpdateLogObj->save();
//                    }
                    if ($editionFee != $customerOrderPriceObj['edition_fee']) {
                        $priceMessageContent .= "版费有修改rnrn";
                        $customerOrderDealUpdateLogObj = \App\Eloquent\Ygt\CustomerOrderDealUpdateLog::firstOrNew(['customer_order_id' => $customerOrderId, 'deal_field_name' => 'edition_fee']);
                        $tmpInsterRow = [
                            'customer_order_id' => $customerOrderId,
                            'deal_field_name' => 'edition_fee',
                            'old_value' => '',
                            'new_value' => $editionFee,
                            'uid' => $userId,
                        ];
                        $customerOrderDealUpdateLogObj->fill($tmpInsterRow);
                        $customerOrderDealUpdateLogObj->save();
                    }
                    if ($freightFee != $customerOrderPriceObj['freight_fee']) {
                        $priceMessageContent .= "运费有修改rnrn";
                        $customerOrderDealUpdateLogObj = \App\Eloquent\Ygt\CustomerOrderDealUpdateLog::firstOrNew(['customer_order_id' => $customerOrderId, 'deal_field_name' => 'freight_fee']);
                        $tmpInsterRow = [
                            'customer_order_id' => $customerOrderId,
                            'deal_field_name' => 'freight_fee',
                            'old_value' => '',
                            'new_value' => $freightFee,
                            'uid' => $userId,
                        ];
                        $customerOrderDealUpdateLogObj->fill($tmpInsterRow);
                        $customerOrderDealUpdateLogObj->save();
                    }
                    if ($taxPoint != $customerOrderPriceObj['tax_point']) {
                        $priceMessageContent .= "税点有修改rnrn";
                        $customerOrderDealUpdateLogObj = \App\Eloquent\Ygt\CustomerOrderDealUpdateLog::firstOrNew(['customer_order_id' => $customerOrderId, 'deal_field_name' => 'tax_point']);
                        $tmpInsterRow = [
                            'customer_order_id' => $customerOrderId,
                            'deal_field_name' => 'tax_point',
                            'old_value' => '',
                            'new_value' => $taxPoint,
                            'uid' => $userId,
                        ];
                        $customerOrderDealUpdateLogObj->fill($tmpInsterRow);
                        $customerOrderDealUpdateLogObj->save();
                    }


                    $tmpInsterRow = [
                        'customer_price' => $price,//订单价格已确定
                        'edition_fee_type' => $editionFeeType,
                        'edition_fee' => $editionFee,
                        'freight_fee' => $freightFee,
                        'tax_point' => $taxPoint,
                        'status' => 5,//客户不同意价格，需销售员重新确认
                    ];


                    $customerOrderPriceObj->fill($tmpInsterRow);
                    $customerOrderPriceObj->save();

                    //保存价格记录
                    $customerOrderPriceLogObj = \App\Eloquent\Ygt\CustomerOrderPriceLog::firstOrNew(['id' => '']);
                    $tmpInsterRow = [
                        'customer_order_id' => $customerOrderId,
                        'customer_order_price_id' => $customerOrderPriceObj->id,
                        'price' => $price,
                        'uid' => $userId,
                        'type' => 4,//4-客户修改价格
                    ];
                    $customerOrderPriceLogObj->fill($tmpInsterRow);
                    $customerOrderPriceLogObj->save();


                    //消息内容
                    $messageContent = $this->getCustomerOrderRelateMessageContent(
                        $customerOrderId,
                        [
                            '工艺名称'=>'',
                            '单位名称'=>'',
                            '品名'=>'',
                            '成品规格'=>'',
                            '单价'=>$price,
                            '数量'=>'',
                            '交货日期'=>'',
                            '订单号'=>'',
                        ],
                        $customerOrderRow
                    );

                    $data = [
                        'company_id' => $companyId,
                        'privilege_id' => '',
                        'form_user_id' => $userId,
                        'to_user_id' => $customerOrderPriceObj['sale_uid'],
                        'foreign_key' => $customerOrderId,
                        'type' => 19,//type待定
                        'type_id' => $customerOrderId,
                        'title' => $customerOrderRow['order_title'],
                        'content' => $messageContent,
                        'theme' =>'客户修改需求重新询单'
                    ];

                    UserMessage::sendCustomerOrderMessage($data);
                }

                break;
            case 'sellerSubmit'://sellerSubmit -- 销售员提交
                if ($submitType == 'agree') {
                    //删除原来的修改记录
                    \App\Eloquent\Ygt\CustomerOrderDealUpdateLog::where(['customer_order_id' => $customerOrderId])->delete();

                    //修改状态
                    $customerOrderPriceObj = \App\Eloquent\Ygt\CustomerOrderPrice::firstOrNew(['customer_order_id' => $customerOrderId]);
                    $tmpInsterRow = [
                        'sale_price' => $customerOrderPriceObj['customer_price'],//订单价格已确定
                        'deal_price' => $customerOrderPriceObj['customer_price'],//订单价格已确定
                        'status' => 100,//订单价格已确定
                    ];
                    $customerOrderPriceObj->fill($tmpInsterRow);
                    $customerOrderPriceObj->save();

                    //保存价格记录
                    $customerOrderPriceLogObj = \App\Eloquent\Ygt\CustomerOrderPriceLog::firstOrNew(['id' => '']);
                    $tmpInsterRow = [
                        'customer_order_id' => $customerOrderId,
                        'customer_order_price_id' => $customerOrderPriceObj->id,
                        'price' => $price,
                        'uid' => $userId,
                        'type' => 5,//5-销售员确认价格
                    ];
                    $customerOrderPriceLogObj->fill($tmpInsterRow);
                    $customerOrderPriceLogObj->save();


                    //修改订单标示
                    $customerOrderObj = \App\Eloquent\Ygt\CustomerOrder::where(['id' => $customerOrderId])->first();
                    $customerOrderObj->is_deal_price = 1;
                    $customerOrderObj->save();

                    //消息内容
                    $messageContent = $this->getCustomerOrderRelateMessageContent(
                        $customerOrderId,
                        [
                            '工艺名称'=>'',
                            '单位名称'=>'',
                            '品名'=>'',
                            '成品规格'=>'',
                            '数量'=>'',
                            '交货日期'=>'',
                            '单价'=>$price,
                            '订单号'=>'',
                        ],
                        $customerOrderRow
                    );

                    //发送消息给客户
                    $data = [
                        'company_id' => 2,
                        'privilege_id' => '',
                        'form_user_id' => $userId,
                        'to_user_id' => $customerOrderPriceObj['customer_uid'],
                        'foreign_key' => $customerOrderId,
                        'type' => 19,//type待定
                        'type_id' => $customerOrderId,
                        'title' => $customerOrderRow['order_title'],
                        'content' => $messageContent,
                         'theme' =>'订单已确认'
                    ];
                    UserMessage::sendCustomerOrderMessage($data);

                    //发消息给下单人
                    //消息内容
                    $messageContent = $this->getCustomerOrderRelateMessageContent(
                        $customerOrderId,
                        [
                            '工艺名称'=>'',
                            '客户名称'=>'',
                            '单位名称'=>'',
                            '品名'=>'',
                            '成品规格'=>'',
                            '数量'=>'',
//                            '单价'=>$price,
                            '交货日期'=>'',
                            '订单号'=>'',
                        ],
                        $customerOrderRow
                    );
                    if($customerOrderPriceObj['singleperson_uid']){
                        $data = [
                            'company_id' => $companyId,
                            'privilege_id' => '',
                            'form_user_id' => $userId,
                            'to_user_id' => $customerOrderPriceObj['singleperson_uid'],
                            'foreign_key' => $customerOrderId,
                            'type' => 16,//type待定
                            'type_id' => $customerOrderId,
                            'title' => $customerOrderRow['order_title'],
                            'content' => $messageContent,
                            'theme'=> '订单已确认签署'
                        ];
                        UserMessage::sendCustomerOrderMessage($data);
                    }else{
                        //如果议价过程中未涉及到下单人，给所有有下单权限的人发消息
                        //获取下单权限的用户
                        $privilegeIdList = \App\Engine\OrderEngine::getPrivilegeByNode($companyId, 1);
                        foreach ($privilegeIdList as $privilegeId) {
                            if ($privilegeId) {
                                $data = [
                                    'company_id' => $companyId,
                                    'privilege_id' => $privilegeId,
                                    'form_user_id' => $userId,
                                    'to_user_id' => '',
                                    'foreign_key' => $customerOrderId,
                                    'type' => 16,//type待定
                                    'type_id' => $customerOrderId,
                                    'title' => $customerOrderRow['order_title'],
                                    'content' => $messageContent,
                                    'theme'=> '订单已确认签署'
                                ];
                                UserMessage::sendCustomerOrderMessage($data);
                            }
                        }
                    }



                } else {
                    //删除原来的修改记录
                    \App\Eloquent\Ygt\CustomerOrderDealUpdateLog::where(['customer_order_id' => $customerOrderId])->delete();
                    //修改订单消息
                    $messageContent = $this->updateCustomerOrderInfo($customerOrderId, $userId);

                    //修改状态
                    $customerOrderPriceObj = \App\Eloquent\Ygt\CustomerOrderPrice::firstOrNew(['customer_order_id' => $customerOrderId]);

                    //判断价格、运费、版费、税点是否有修改
                    $priceMessageContent = '';
                    if ($price != $customerOrderPriceObj['customer_price']) {
                        $priceMessageContent .= "价格有修改rnrn";
                    }
//                    if($editionFeeType != $customerOrderPriceObj['edition_fee_type']){
//                        $priceMessageContent.="版费类型有修改rnrn";
//                        $customerOrderDealUpdateLogObj = \App\Eloquent\Ygt\CustomerOrderDealUpdateLog::firstOrNew(['customer_order_id'=>$customerOrderId,'deal_field_name'=>'edition_fee_type']);
//                        $tmpInsterRow = [
//                            'customer_order_id' => $customerOrderId,
//                            'deal_field_name' => 'edition_fee_type',
//                            'old_value' => '',
//                            'new_value' => $editionFeeType,
//                            'uid' => $userId,
//                        ];
//                        $customerOrderDealUpdateLogObj->fill($tmpInsterRow);
//                        $customerOrderDealUpdateLogObj->save();
//                    }
                    if ($editionFee != $customerOrderPriceObj['edition_fee']) {
                        $priceMessageContent .= "版费有修改rnrn";
                        $customerOrderDealUpdateLogObj = \App\Eloquent\Ygt\CustomerOrderDealUpdateLog::firstOrNew(['customer_order_id' => $customerOrderId, 'deal_field_name' => 'edition_fee']);
                        $tmpInsterRow = [
                            'customer_order_id' => $customerOrderId,
                            'deal_field_name' => 'edition_fee',
                            'old_value' => '',
                            'new_value' => $editionFee,
                            'uid' => $userId,
                        ];
                        $customerOrderDealUpdateLogObj->fill($tmpInsterRow);
                        $customerOrderDealUpdateLogObj->save();
                    }
                    if ($freightFee != $customerOrderPriceObj['freight_fee']) {
                        $priceMessageContent .= "运费有修改rnrn";
                        $customerOrderDealUpdateLogObj = \App\Eloquent\Ygt\CustomerOrderDealUpdateLog::firstOrNew(['customer_order_id' => $customerOrderId, 'deal_field_name' => 'freight_fee']);
                        $tmpInsterRow = [
                            'customer_order_id' => $customerOrderId,
                            'deal_field_name' => 'freight_fee',
                            'old_value' => '',
                            'new_value' => $freightFee,
                            'uid' => $userId,
                        ];
                        $customerOrderDealUpdateLogObj->fill($tmpInsterRow);
                        $customerOrderDealUpdateLogObj->save();
                    }
                    if ($taxPoint != $customerOrderPriceObj['tax_point']) {
                        $priceMessageContent .= "税点有修改rnrn";
                        $customerOrderDealUpdateLogObj = \App\Eloquent\Ygt\CustomerOrderDealUpdateLog::firstOrNew(['customer_order_id' => $customerOrderId, 'deal_field_name' => 'tax_point']);
                        $tmpInsterRow = [
                            'customer_order_id' => $customerOrderId,
                            'deal_field_name' => 'tax_point',
                            'old_value' => '',
                            'new_value' => $taxPoint,
                            'uid' => $userId,
                        ];
                        $customerOrderDealUpdateLogObj->fill($tmpInsterRow);
                        $customerOrderDealUpdateLogObj->save();
                    }

                    $tmpInsterRow = [
                        'sale_price' => $price,//订单价格已确定
                        'edition_fee_type' => $editionFeeType,
                        'edition_fee' => $editionFee,
                        'freight_fee' => $freightFee,
                        'tax_point' => $taxPoint,
                        'status' => 6,//销售员不同意客户的价格，提交新价格需客户重新确认
                    ];
                    $customerOrderPriceObj->fill($tmpInsterRow);
                    $customerOrderPriceObj->save();

                    //保存价格记录
                    $customerOrderPriceLogObj = \App\Eloquent\Ygt\CustomerOrderPriceLog::firstOrNew(['id' => '']);
                    $tmpInsterRow = [
                        'customer_order_id' => $customerOrderId,
                        'customer_order_price_id' => $customerOrderPriceObj->id,
                        'price' => $price,
                        'uid' => $userId,
                        'type' => 6,//6-销售员修改价格
                    ];
                    $customerOrderPriceLogObj->fill($tmpInsterRow);
                    $customerOrderPriceLogObj->save();


                    //发送消息给客商
                    $customerId = $customerOrderRow['customer_name'];
                    //获取客户的用户ID
                    $toUserId = \App\Eloquent\Ygt\Customer::where(['id' => $customerId])->first()->user_id;
//                    $customerId = $customerOrderRow['customer_name'];

                    //消息内容
                    $messageContent = $this->getCustomerOrderRelateMessageContent(
                        $customerOrderId,
                        [
                            '工艺名称'=>'',
                            '单位名称'=>'',
                            '品名'=>'',
                            '成品规格'=>'',
                            '单价'=>$price,
                            '数量'=>'',
                            '交货日期'=>'',
                            '订单号'=>'',
                        ],
                        $customerOrderRow
                    );

                    $data = [
                        'company_id' => 2,
                        'privilege_id' => '',
                        'form_user_id' => $userId,
                        'to_user_id' => $toUserId,
                        'foreign_key' => $customerOrderId,
                        'type' => 19,//type待定
                        'type_id' => $customerOrderId,
                        'title' => $customerOrderRow['order_title'],
                        'content' => $messageContent,
                        'theme'=>'订单重新报价'
                    ];
                    UserMessage::sendCustomerOrderMessage($data);
                }
                break;
            case 'directConfirmPrice': //directConfirmPrice - 直接确认订单价格
                if (!$price) {
                    return [
                        'code' => 1,
                        'message' => '请填写价格'
                    ];
                }

                //删除原来的修改记录
                \App\Eloquent\Ygt\CustomerOrderDealUpdateLog::where(['customer_order_id' => $customerOrderId])->delete();

                //修改状态
                $customerOrderPriceObj = \App\Eloquent\Ygt\CustomerOrderPrice::firstOrNew(['customer_order_id' => $customerOrderId]);
                $tmpInsterRow = [
                    'sale_price' => $price,//订单价格已确定
                    'deal_price' => $price,//订单价格已确定
                    'edition_fee_type' => $editionFeeType,
                    'edition_fee' => $editionFee,
                    'freight_fee' => $freightFee,
                    'tax_point' => $taxPoint,
                    'status' => 100,//订单价格已确定
                ];
                $customerOrderPriceObj->fill($tmpInsterRow);
                $customerOrderPriceObj->save();

                //保存价格记录
                $customerOrderPriceLogObj = \App\Eloquent\Ygt\CustomerOrderPriceLog::firstOrNew(['id' => '']);
                $tmpInsterRow = [
                    'customer_order_id' => $customerOrderId,
                    'customer_order_price_id' => $customerOrderPriceObj->id,
                    'price' => $price,
                    'uid' => $userId,
                    'type' => 7,//7-直接确认价格
                ];
                $customerOrderPriceLogObj->fill($tmpInsterRow);
                $customerOrderPriceLogObj->save();

                //修改订单标示
                $customerOrderObj = \App\Eloquent\Ygt\CustomerOrder::where(['id' => $customerOrderId])->first();
                $customerOrderObj->is_deal_price = 1;
                $customerOrderObj->save();

                //消息内容
                $messageContent = $this->getCustomerOrderRelateMessageContent(
                    $customerOrderId,
                    [
                        '工艺名称'=>'',
                        '单位名称'=>'',
                        '品名'=>'',
                        '成品规格'=>'',
                        '数量'=>'',
                        '交货日期'=>'',
                        '单价'=>$price,
                        '订单号'=>'',
                    ],
                    $customerOrderRow
                );

                //发送消息给客户
                $data = [
                    'company_id' => 2,
                    'privilege_id' => '',
                    'form_user_id' => $userId,
                    'to_user_id' => $customerOrderPriceObj['customer_uid'],
                    'foreign_key' => $customerOrderId,
                    'type' => 19,//type待定
                    'type_id' => $customerOrderId,
                    'title' => $customerOrderRow['order_title'],
                    'content' => $messageContent,
                    'theme' =>'订单已确认'
                ];
                UserMessage::sendCustomerOrderMessage($data);

                //发消息给下单人
                //消息内容
                $messageContent = $this->getCustomerOrderRelateMessageContent(
                    $customerOrderId,
                    [
                        '工艺名称'=>'',
                        '单位名称'=>'',
                        '品名'=>'',
                        '成品规格'=>'',
                        '数量'=>'',
                        '交货日期'=>'',
//                        '单价'=>$price,
                        '订单号'=>'',
                    ],
                    $customerOrderRow
                );

                if($customerOrderPriceObj['singleperson_uid']){
                    $data = [
                        'company_id' => $companyId,
                        'privilege_id' => '',
                        'form_user_id' => $userId,
                        'to_user_id' => $customerOrderPriceObj['singleperson_uid'],
                        'foreign_key' => $customerOrderId,
                        'type' => 16,//type待定
                        'type_id' => $customerOrderId,
                        'title' => $customerOrderRow['order_title'],
                        'content' => $messageContent,
                        'theme' =>'订单已确认签署'
                    ];
                    UserMessage::sendCustomerOrderMessage($data);
                }else{
                    //如果议价过程中未涉及到下单人，给所有有下单权限的人发消息
                    //获取下单权限的用户
                    $privilegeIdList = \App\Engine\OrderEngine::getPrivilegeByNode($companyId, 1);
                    foreach ($privilegeIdList as $privilegeId) {
                        if ($privilegeId) {
                            $data = [
                                'company_id' => $companyId,
                                'privilege_id' => $privilegeId,
                                'form_user_id' => $userId,
                                'to_user_id' => '',
                                'foreign_key' => $customerOrderId,
                                'type' => 16,//type待定
                                'type_id' => $customerOrderId,
                                'title' => $customerOrderRow['order_title'],
                                'content' => $messageContent,
                                'theme' =>'订单已确认签署'
                            ];
                            UserMessage::sendCustomerOrderMessage($data);
                        }
                    }
                }



                break;
            default:
                return [
                    'code' => '4',
                    'message' => '操作异常'
                ];
                break;
        }

        return [
            'code' => 0,
            'message' => '操作成功'
        ];

//        //销售员角色提交价格
//        if($customerOrderRow['customer_name'] != $userId){
//            if(!$dealType){
//                //第一次提交价格
//                 = \App\Eloquent\Ygt\CustomerOrderPrice::firstOrNew(['customer_order_id'=>$customerOrderId]);
//                if($customerOr$customerOrderPriceObjderPriceObj->count()){
//                    return [
//                        'code' => '1',
//                        'message' => '操作异常'
//                    ];
//                }
//
//                $eidtRow = [
//                    'customer_order_id' => $customerOrderId,
//                    'sale_price' => $price,
//                    'status' => 1,
//                    'sale_uid' => $userId,
//                    'customer_uid' => $customerOrderRow['customer_name'],
//                ];
//                $customerOrderPriceObj->fill($eidtRow);
//                $customerOrderPriceObj->save();
//
//                //发送消息
//                $data           = [
//                    'company_id'=> $customerOrderRow['company_id'],
//                    'privilege_id'=> '',
//                    'form_user_id'=> $userId,
//                    'to_user_id'=> $customerOrderRow['customer_name'],
//                    'foreign_key'=> $customerOrderId,
//                    'type'=>19,
//                    'type_id'=>$customerOrderId,
//                    'title'=>'订单价格',
//                    'content'=>'销售员提交了新价格'
//                ];
//                \App\Eloquent\Ygt\UserMessage::sendCustomerOrderMessage($data);
//            }else{
//                //对客户新提的价格进行处理
//                if($dealType == 'agree'){
//                    //双方价格确定
//                    $customerOrderPriceObj = \App\Eloquent\Ygt\CustomerOrderPrice::where(['customer_order_id'=>$customerOrderId])->first();
//                    if($customerOrderPriceObj){
//                        if($customerOrderPriceObj->status == 2){
//                            //价格确定
//                            $eidtRow = [
//                                'customer_order_id' => $customerOrderId,
//                                'customer_price' => $customerOrderPriceObj->sale_price,
//                                'deal_price' => $customerOrderPriceObj->sale_price,
//                                'status' => 3,
//                            ];
//                            $customerOrderPriceObj->fill($eidtRow);
//                            $customerOrderPriceObj->save();
//
//                            //发送消息
//                            $data           = [
//                                'company_id'=> $customerOrderRow['company_id'],
//                                'privilege_id'=> '',
//                                'form_user_id'=> $userId,
//                                'to_user_id'=> $customerOrderRow['customer_name'],
//                                'foreign_key'=> $customerOrderId,
//                                'type'=>19,
//                                'type_id'=>$customerOrderId,
//                                'title'=>'订单价格',
//                                'content'=>'销售员同意了价格'
//                            ];
//                            \App\Eloquent\Ygt\UserMessage::sendCustomerOrderMessage($data);
//
//                        }else{
//                            return [
//                                'code' => '3',
//                                'message' => '操作异常'
//                            ];
//                        }
//                    }else{
//                        return [
//                            'code' => '2',
//                            'message' => '操作异常'
//                        ];
//                    }
//
//                }elseif($dealType == 'reject'){
//                    //价格确定
//                    $customerOrderPriceObj = \App\Eloquent\Ygt\CustomerOrderPrice::where(['customer_order_id'=>$customerOrderId])->first();
//                    $eidtRow = [
//                        'sale_price' => $price,
//                        'status' => 1,
//                    ];
//                    $customerOrderPriceObj->fill($eidtRow);
//                    $customerOrderPriceObj->save();
//
//                    //发送消息
//                    $data           = [
//                        'company_id'=> $customerOrderRow['company_id'],
//                        'privilege_id'=> '',
//                        'form_user_id'=> $userId,
//                        'to_user_id'=> $customerOrderRow['customer_name'],
//                        'foreign_key'=> $customerOrderId,
//                        'type'=>19,
//                        'type_id'=>$customerOrderId,
//                        'title'=>'订单价格',
//                        'content'=>'销售员不同意提交的价格，并提交了新价格'
//                    ];
//                    \App\Eloquent\Ygt\UserMessage::sendCustomerOrderMessage($data);
//
//
//                }else{
//                    return [
//                        'code' => '1',
//                        'message' => '操作异常'
//                    ];
//                }
//
//            }

//            return '操作成功';
//        }
//
//        //客商提交价格
//        if($customerOrderRow['customer_name'] == $userId){
//            //对销售员新提的价格进行处理
//            if($dealType == 'agree'){
//                //双方价格确定
//                $customerOrderPriceObj = \App\Eloquent\Ygt\CustomerOrderPrice::where(['customer_order_id'=>$customerOrderId])->first();
//                if($customerOrderPriceObj){
//                    if($customerOrderPriceObj->status == 1){
//                        //价格确定
//                        $eidtRow = [
//                            'customer_order_id' => $customerOrderId,
//                            'sale_price' => $customerOrderPriceObj->customer_price,
//                            'deal_price' => $customerOrderPriceObj->customer_price,
//                            'status' => 3,
//                        ];
//                        $customerOrderPriceObj->fill($eidtRow);
//                        $customerOrderPriceObj->save();
//
//                        //发送消息
//                        $data           = [
//                            'company_id'=> $customerOrderRow['company_id'],
//                            'privilege_id'=> '',
//                            'form_user_id'=> $userId,
//                            'to_user_id'=> $customerOrderPriceObj->sale_uid,
//                            'foreign_key'=> $customerOrderId,
//                            'type'=>19,
//                            'type_id'=>$customerOrderId,
//                            'title'=>'订单价格',
//                            'content'=>'客商同意了价格'
//                        ];
//                        \App\Eloquent\Ygt\UserMessage::sendCustomerOrderMessage($data);
//
//                    }else{
//                        return [
//                            'code' => '3',
//                            'message' => '操作异常'
//                        ];
//                    }
//                }else{
//                    return [
//                        'code' => '2',
//                        'message' => '操作异常'
//                    ];
//                }
//
//            }elseif($dealType == 'reject'){
//                //价格确定
//                $customerOrderPriceObj = \App\Eloquent\Ygt\CustomerOrderPrice::where(['customer_order_id'=>$customerOrderId])->first();
//                $eidtRow = [
//                    'customer_price' => $price,
//                    'status' => 2,
//                ];
//                $customerOrderPriceObj->fill($eidtRow);
//                $customerOrderPriceObj->save();
//
//                //发送消息
//                $data           = [
//                    'company_id'=> $customerOrderRow['company_id'],
//                    'privilege_id'=> '',
//                    'form_user_id'=> $userId,
//                    'to_user_id'=> $customerOrderPriceObj->sale_uid,
//                    'foreign_key'=> $customerOrderId,
//                    'type'=>19,
//                    'type_id'=>$customerOrderId,
//                    'title'=>'订单价格',
//                    'content'=>'客商不同意提交的价格，并提交了新价格'
//                ];
//                \App\Eloquent\Ygt\UserMessage::sendCustomerOrderMessage($data);
//
//            }else{
//                return [
//                    'code' => '1',
//                    'message' => '操作异常'
//                ];
//            }
//
//
//            return '操作成功';
//        }
//
//
//        return [
//            'code' => '4',
//            'message' => '操作异常'
//        ];
    }

    private function updateCustomerOrderInfo($customerOrderId, $userId)
    {
        ////修改订单基础信息&工序信息
        $fieldChangeList = [];//


        //订单基础信息
        $customerOrderRow = \App\Eloquent\Ygt\CustomerOrder::where(['id' => $customerOrderId])->first();

        $tmpFiledChangeList = [];
        foreach ($customerOrderRow->toArray() as $fieldName => $fieldValue) {
            $dealFieldName = 'base___' . $fieldName;
            $tmpPostValue = request($dealFieldName);

            $companyId = $customerOrderRow['company_id'];
            $orderBaseFieldList = OrderFieldCompany::getActiveFieldList($companyId);
            $filedType = '';
            foreach ($orderBaseFieldList as $orderBaseFieldRow){
                if($fieldName == $orderBaseFieldRow['field_name']){
                    $filedType = $orderBaseFieldRow['field_type'];
                    break;
                }
            }


            if($filedType && $filedType == 17){
                //比对版的信息&将值转换为ID
                //获取原ID对应的数据
                $prePlateInfo = \App\Eloquent\Ygt\CreateOrderPlate::where(['id'=>$fieldValue])->first();
                if($prePlateInfo['content'] != $tmpPostValue){
                    //限制-版数量想加不能超过产品数量
                    $tmpPlateBranch = json_decode(htmlspecialchars_decode($tmpPostValue), true);
                    $tmpPlateNumAll = 0;
                    if(isset($tmpPlateBranch['branch']['colourplate'])){
                        foreach ($tmpPlateBranch['branch']['colourplate'] as $tmpRow){
                            $tmpPlateNumAll += $tmpRow['num'];
                        }
                    }

                    if($tmpPlateNumAll && ($tmpPlateNumAll > $customerOrderRow['product_num']) ){
                        return [
                            'code' => 1,
                            'message' => '版支总数量不能超过产品数量',
                        ];
                    }


                    //新数据存表&获取ID
                    $tmpObj = \App\Eloquent\Ygt\CreateOrderPlate::firstOrNew(['id'=>'']);
                    $tmpInsertRow = [
                        'type' => 1,
                        'relate_id' => $customerOrderId,
                        'field_name' => $fieldName,
                        'content' => $tmpPostValue,
                    ];

                    $tmpObj->fill($tmpInsertRow);
                    $tmpObj->save();
                    $createOrderPlateId = $tmpObj->id;

                    $tmpPostValue = $createOrderPlateId;//转换为ID用于后续判断及存值

                }
                else{
                    $tmpPostValue = $fieldValue;
                }
            }
            else if($filedType && $filedType == 4){
                $tempArr = [
                    'old'=>$tmpPostValue,
                ];
                $tempArr = OrderEngine::handleInput($tempArr,'old',$filedType,'purchase_info');
                $tmpPostValue = $tempArr['old'];

                if(isset($tempArr['purchase_info']) && !empty($tempArr['purchase_info'])){
                    //获取相关订单信息
                    $customerOrderInfo = CustomerOrder::where('id','=',$customerOrderId)->first()->toArray();
                    $purchase_info = $tempArr['purchase_info'];
                    foreach($purchase_info as $val){
                        OrderMaterialPurchaseMark::updateOrCreate(
                            [
                                'customer_order_pre_id'=>$customerOrderInfo['order_pre_id'],
                                'customer_order_id'=>$customerOrderId,
                                'material_id'=>$val['id'],
                            ],
                            [
                                'is_purchase'=>$val['is_purchase']
                            ]
                        );
                    }
                }
            }

            if (isset($tmpPostValue)) {
                if ($tmpPostValue != $fieldValue) {//已修改

                    //修改订单信息
                    $customerOrderRow->$fieldName = $tmpPostValue;
                    //保存新的修改记录
                    $customerOrderDealUpdateLogObj = \App\Eloquent\Ygt\CustomerOrderDealUpdateLog::firstOrNew(['customer_order_id' => $customerOrderId, 'deal_field_name' => $dealFieldName]);

                    $tmpInsterRow = [
                        'customer_order_id' => $customerOrderId,
                        'deal_field_name' => $dealFieldName,
                        'old_value' => $fieldValue,
                        'new_value' => $tmpPostValue,
                        'uid' => $userId,
                    ];
                    $customerOrderDealUpdateLogObj->fill($tmpInsterRow);
                    $customerOrderDealUpdateLogObj->save();

                    //获取字段对应的名称
                    $orderFieldCompanyObj = \App\Eloquent\Ygt\OrderFieldCompany::where(['field_name' => $fieldName, 'company_id' => $customerOrderRow['company_id']])->first();
                    if ($orderFieldCompanyObj) {
                        $tmpFiledChangeList['title'] = '基础信息';
                        $tmpFiledChangeList['list'][] = [
                            'title' => $orderFieldCompanyObj['title'],
                        ];
                    }




                }
            }
        }

        if (!empty($tmpFiledChangeList)) {
            $fieldChangeList[] = $tmpFiledChangeList;
        }

        $customerOrderRow->save();

        //工序信息
        $customerOrderProcessList = \App\Eloquent\Ygt\CustomerOrderProcess::where(['order_id' => $customerOrderId])->get();
        foreach ($customerOrderProcessList as $customerOrderProcessRow) {
            $tmpFiledChangeList = [];

            foreach ($customerOrderProcessRow->toArray() as $fieldName => $fieldValue) {
                $dealFieldName = $customerOrderProcessRow['id'] . '___' . $fieldName;
                $tmpPostValue = request($dealFieldName);


                $processFieldList = Process::getFieldListByProcessId($customerOrderProcessRow['process_type']);
                $filedType = '';
                foreach ($processFieldList as $processFieldRow){
                    if($fieldName == $processFieldRow['field_name']){
                        $filedType = $processFieldRow['field_type'];
                        break;
                    }
                }


                if($filedType && $filedType == 17){
                    //比对版的信息&将值转换为ID
                    //获取原ID对应的数据
                    $prePlateInfo = \App\Eloquent\Ygt\CreateOrderPlate::where(['id'=>$fieldValue])->first();
                    if($prePlateInfo['content'] != $tmpPostValue){
                        //新数据存表&获取ID
                        $tmpObj = \App\Eloquent\Ygt\CreateOrderPlate::firstOrNew(['id'=>'']);
                        $tmpInsertRow = [
                            'type' => 1,
                            'relate_id' => $customerOrderId,
                            'field_name' => $fieldName,
                            'content' => $tmpPostValue,
                        ];

                        $tmpObj->fill($tmpInsertRow);
                        $tmpObj->save();
                        $createOrderPlateId = $tmpObj->id;

                        $tmpPostValue = $createOrderPlateId;//转换为ID用于后续判断及存值

                    }else{
                        $tmpPostValue = $fieldValue;
                    }
                }elseif($filedType && $filedType == 22){
                    //比对版的信息&将值转换为ID
                    //获取原ID对应的数据
                    $preProcessProductInfo = \App\Eloquent\Ygt\CreateOrderProcessProduct::where(['id'=>$fieldValue])->first();
                    if($preProcessProductInfo['content'] != $tmpPostValue){
                        //新数据存表&获取ID
                        $tmpObj = \App\Eloquent\Ygt\CreateOrderProcessProduct::firstOrNew(['id'=>'']);
                        $tmpInsertRow = [
                            'type' => 1,
                            'relate_id' => $customerOrderId,
                            'field_name' => $fieldName,
                            'content' => $tmpPostValue,
                        ];

                        $tmpObj->fill($tmpInsertRow);
                        $tmpObj->save();
                        $createOrderPlateId = $tmpObj->id;

                        $tmpPostValue = $createOrderPlateId;//转换为ID用于后续判断及存值

                    }else{
                        $tmpPostValue = $fieldValue;
                    }
                }
                else if($filedType && $filedType == 4){
                    $tempArr = [
                        'old'=>$tmpPostValue,
                    ];
                    $tempArr = OrderEngine::handleInput($tempArr,'old',$filedType,'purchase_info');
                    $tmpPostValue = $tempArr['old'];
                    if(isset($tempArr['purchase_info']) && !empty($tempArr['purchase_info'])){
                        //获取相关订单信息
                        $customerOrderInfo = CustomerOrder::where('id','=',$customerOrderId)->first()->toArray();
                        $purchase_info = $tempArr['purchase_info'];
                        foreach($purchase_info as $val){
                            OrderMaterialPurchaseMark::updateOrCreate(
                                [
                                    'customer_order_pre_id'=>$customerOrderInfo['order_pre_id'],
                                    'customer_order_id'=>$customerOrderId,
                                    'material_id'=>$val['id'],
                                ],
                                [
                                    'is_purchase'=>$val['is_purchase']
                                ]
                            );
                        }
                    }
                }


                if (isset($tmpPostValue)) {
                    if ($tmpPostValue != $fieldValue) {//已修改
                        //修改订单信息
                        $customerOrderProcessRow->$fieldName = $tmpPostValue;
                        //保存新的修改记录
                        $customerOrderDealUpdateLogObj = \App\Eloquent\Ygt\CustomerOrderDealUpdateLog::firstOrNew(['customer_order_id' => $customerOrderId, 'deal_field_name' => $dealFieldName]);

                        $tmpInsterRow = [
                            'customer_order_id' => $customerOrderId,
                            'deal_field_name' => $dealFieldName,
                            'old_value' => $fieldValue,
                            'new_value' => $tmpPostValue,
                            'uid' => $userId,
                        ];
                        $customerOrderDealUpdateLogObj->fill($tmpInsterRow);
                        $customerOrderDealUpdateLogObj->save();

                        //获取工序名称
                        //获取字段对应的名称
                        $processFieldCompanyObj = \App\Eloquent\Ygt\ProcessFieldCompany::where(['field_name' => $fieldName, 'company_id' => $customerOrderRow['company_id']])->first();
                        if ($processFieldCompanyObj) {
                            $processTitle = \App\Eloquent\Ygt\Process::getOneValueById($customerOrderProcessRow['process_type'], 'title');
                            $tmpFiledChangeList['title'] = $processTitle;
                            $tmpFiledChangeList['list'][] = [
                                'title' => $processFieldCompanyObj['title'],
                            ];
                        }


                    }
                }
            }
            $customerOrderProcessRow->save();

            if (!empty($tmpFiledChangeList)) {
                $fieldChangeList[] = $tmpFiledChangeList;
            }
        }


        //生成消息内容
        $updateLogMessageContent = '';
        foreach ($fieldChangeList as $fieldChangeRow) {
            $updateLogMessageContent .= "rnrn" . $fieldChangeRow['title'] . "：rnrn";
            foreach ($fieldChangeRow['list'] as $filedRow) {
                $updateLogMessageContent .= $filedRow['title'] . "有修改rnrn";
            }
        }


        //有调整，只需要显示订单有调整即可 20180625 zhuyujun
        if ($updateLogMessageContent) {
            $updateLogMessageContent = '订单有修改';
        }


        return $updateLogMessageContent;

    }


    //设置工单员工计件工资
    public function setOrderPieceWage()
    {
        $userId = Func::getHeaderValueByName('userid');
        $userInfo = DepartmentUser::getCurrentInfo($userId)->toArray();
        $companyId = $userInfo['company_id'];

        $orderProcessCourseId = request('order_process_course_id');//员工工单ID
        $pieceWage = request('piece_wage');//计件工资


        $orderProcessCourseRow = \App\Eloquent\Ygt\OrderProcessCourse::where(['id' => $orderProcessCourseId])->first()->toArray();
        $orderProcessRow = \App\Eloquent\Ygt\OrderProcess::where(['id' => $orderProcessCourseRow['order_process_id']])->first()->toArray();
        $orderRow = \App\Eloquent\Ygt\Order::where(['id' => $orderProcessRow['order_id']])->first()->toArray();


        $orderWageObj = OrderWage::firstOrNew(['order_process_course_id' => $orderProcessCourseId]);
        $editRow = [
            'order_id' => $orderRow['id'],
            'order_process_id' => $orderProcessRow['id'],
            'order_process_course_id' => $orderProcessCourseRow['id'],
            'employee_id' => $orderProcessCourseRow['uid'],
            'manager_id' => $userId,
            'piece_wage' => $pieceWage,
        ];
        $orderWageObj->fill($editRow);
        $orderWageObj->save();

        return '操作成功';
    }


    //批量设置工单员工计件工资
    public function setOrderPieceWageAll()
    {
        $userId = Func::getHeaderValueByName('userid');
        $userInfo = DepartmentUser::getCurrentInfo($userId)->toArray();
        $companyId = $userInfo['company_id'];

        $orderProcessId = request('order_process_id');//员工工单ID
        $privilegeId = request('privilege_id');//工序工单对应的
        $pieceWage = request('piece_wage');//计件工资

        //获取角色下有哪些用户id
        $userIds = \App\Eloquent\Ygt\DepartmentUser::where(['privilege_id' => $privilegeId, 'company_id' => $companyId])->get()->pluck('user_id');

        $orderProcessRow = \App\Eloquent\Ygt\OrderProcess::where(['id' => $orderProcessId])->first()->toArray();
        $orderRow = \App\Eloquent\Ygt\Order::where(['id' => $orderProcessRow['order_id']])->first()->toArray();

        $orderWageObj = OrderWage::firstOrNew(['order_process_id' => $orderProcessId, 'privilege_id' => $privilegeId]);
        $editRow = [
            'order_id' => $orderRow['id'],
            'order_process_id' => $orderProcessRow['id'],
            'privilege_id' => $privilegeId,
            'manager_id' => $userId,
            'piece_wage' => $pieceWage,
        ];
        $orderWageObj->fill($editRow);
        $orderWageObj->save();

        return '操作成功';
    }

    //完整订单打印
    public function getCustomerOrderDetailPrint()
    {
        //数据收集
        $customerOrderId = request('customer_order_id');

        //获取订单信息
        $orderInfo = CustomerOrder::where('id', $customerOrderId)->first()->toArray();


        //订单基础信息字段，目前格式固定 -- 已调整为后台控制 20180131
//        $userId = Func::getHeaderValueByName('userid');
//        $userInfo = DepartmentUser::getCurrentInfo($userId)->toArray();

        $companyId = $orderInfo['company_id'];
        $companyName = '';
        $companyObj = \App\Eloquent\Ygt\Company::where(['id' => $companyId])->first();
        if ($companyObj) {
            $companyName = $companyObj->title;
        }


        $orderBaseFieldList = OrderFieldCompany::getActiveFieldList($companyId);

        $listAll = [];
        $baseInfoList = [];
        //基本信息先固定

        $imageList = [];
        if ($orderInfo['production_case_diagram']) {
            $imageIdList = explode(',', $orderInfo['production_case_diagram']);
            foreach ($imageIdList as $imageId) {
                $imageUrl = ImgUpload::getImgUrlById($imageId, true, false);
                $imageList[] = $imageUrl;
            }
        }
        $customerAddressArr = [];
        $customerName = '';//下单人（客户）
        foreach ($orderBaseFieldList as $key => $row) {
            $leftLabelValue = $row['title'];
            $rightLabelValue = $orderInfo[$row['field_name']];
            if ($row['field_type'] == 9) {//图片处理
                //如果有上传的图片地址，存入数组中
                continue;//另外处理
            } elseif ($row['field_type'] == 8) {//配送地址 处理
                //continue;//另外处理
                $addressWhere = ['id' => $rightLabelValue];
//                $customerAddress = CustomerAddress::getInfo($addressWhere);
                $customerAddress = \App\Eloquent\Ygt\BuyersAddress::withTrashed()->where($addressWhere)->first();
                if ($customerAddress) {
                    $customerAddressArr = $customerAddress->toArray();
                }
                continue;
            } elseif ($row['field_type'] == 21) {//开票资料另外处理
                $buyersInvoiceId = $orderInfo[$row['field_name']];
                continue;
            }


            $rightLabelValue = OrderEngine::getOrderFiledValueTrue($orderInfo[$row['field_name']], $row['field_type']);
            if ($row['field_type'] == 18) {
                $customerName = $rightLabelValue;
            }

            $baseInfoList[] = [
                'leftLabelValue' => $leftLabelValue,
                'rightLabelValue' => $rightLabelValue
            ];
        }
        if (!empty($customerAddressArr)) {
            $baseInfoList[] = [
                'leftLabelValue' => '收货人',
                'rightLabelValue' => $customerAddressArr['consignee']
            ];
            $baseInfoList[] = [
                'leftLabelValue' => '联系手机',
                'rightLabelValue' => $customerAddressArr['phone']
            ];
            $baseInfoList[] = [
                'leftLabelValue' => '区县地址',
                'rightLabelValue' => $customerAddressArr['province_name'] . ' ' . $customerAddressArr['city_name'] . ' ' . $customerAddressArr['area_name']
            ];
            $baseInfoList[] = [
                'leftLabelValue' => '详细地址',
                'rightLabelValue' => $customerAddressArr['address']
            ];
        }

        $list1 = [];
        $customerInvoiceRow = \App\Eloquent\Ygt\BuyersInvoice::where(['id' => $buyersInvoiceId])->first();
        if ($customerInvoiceRow) {
            $list1 = [
                [
                    'leftLabelValue' => '账户名称',
                    'rightLabelValue' => $customerInvoiceRow['account_name'],
                ],
                [
                    'leftLabelValue' => '纳税人识别号',
                    'rightLabelValue' => $customerInvoiceRow['taxpayer_number'],
                ],
                [
                    'leftLabelValue' => '省市区',
                    'rightLabelValue' => $customerInvoiceRow['province_name'] . $customerInvoiceRow['city_name'] . $customerInvoiceRow['area_name'],
                ],
                [
                    'leftLabelValue' => '详细地址',
                    'rightLabelValue' => $customerInvoiceRow['address'],
                ],
                [
                    'leftLabelValue' => '电话',
                    'rightLabelValue' => $customerInvoiceRow['telphone'],
                ],
                [
                    'leftLabelValue' => '开户行',
                    'rightLabelValue' => $customerInvoiceRow['opening_bank'],
                ],
                [
                    'leftLabelValue' => '银行卡号',
                    'rightLabelValue' => $customerInvoiceRow['bank_card_number'],
                ],
            ];

        }


        $baseInfoList = array_merge($baseInfoList, $list1);

        $listAll[] = [
            'titleLabelValue' => '基本信息',
            'list' => $baseInfoList,
            'listImageList' => [],
        ];

        //动态获取工序数据
        //获取订单对应的所有工序
        $orderProcessList = \App\Eloquent\Ygt\CustomerOrderProcess::where(['order_id' => $orderInfo['id']])->get()->toArray();
        foreach ($orderProcessList as $orderProcessInfo) {
            //获取工序信息
//            $orderProcessInfo = CustomerOrderProcess::where(['order_id' => $orderInfo['id'], 'process_type' => $processId])->first();
            $processTitle = Process::getOneValueById($orderProcessInfo['process_type'], 'title');

            $list = [];
            //通过字段类型不同处理
            //获取字段对应的类型1=>'文本',2=>'文本域',3=>'下拉框-跳界面',4=>'跳材料',5=>'有单位',6=>'开关',7=>'时间'
            $processFieldList = Process::getFieldListByProcessId($orderProcessInfo['process_type']);
            foreach ($processFieldList as $processFieldRow) {
                $tmpFiledType = $processFieldRow['field_type'];
                $showTitle = $orderProcessInfo[$processFieldRow['field_name']];//默认展示字段的内容
                if ($tmpFiledType == 4) {//材料选择暂时不显示在
                    //显示每种材料
                    $materialIdList = explode(',', $orderProcessInfo[$processFieldRow['field_name']]);
                    foreach ($materialIdList as $materialId) {
                        if ($materialId) {
                            //获取材料信息（名称）
                            $materialObj = ProductEngine::getProductInfo($materialId);
                            $materialName = $materialId;
                            if ($materialObj) {
                                $materialName = $materialObj->product_name;
                            }

                            $list[] = [
                                'leftLabelValue' => $processFieldRow['title'],
                                'rightLabelValue' => $materialName,
                            ];
                        }
                    }
                    continue;
                }

                $showTitle = OrderEngine::getOrderFiledValueTrue($orderProcessInfo[$processFieldRow['field_name']], $tmpFiledType);

                $list[] = [
                    'leftLabelValue' => $processFieldRow['title'],
                    'rightLabelValue' => $showTitle,
                ];
            }

            $listAll[] = [
                'titleLabelValue' => $processTitle,
                'list' => $list,
                'listImageList' => [],
            ];
        }

        //增加开票信息
        $customerOrderBillingRow = CustomerOrderBilling::where(['customer_order_id' => $customerOrderId])->first();
        if ($customerOrderBillingRow) {
            //附件图片
            $listImageList = [];
            if ($customerOrderBillingRow['img']) {
                $tmpImgIdList = explode(',', $customerOrderBillingRow['img']);
                foreach ($tmpImgIdList as $tmpImgId) {
                    if ($tmpImgId) {
                        $imageUrl = ImgUpload::getImgUrlById($tmpImgId, true, false);
                        $listImageList[] = $imageUrl;
                    }
                }
            }


            //增加开票资料信息
            $list1 = [];
            if (isset($customerOrderBillingRow['invoice_id']) && $customerOrderBillingRow['invoice_id']) {
                $invoiceId = $customerOrderBillingRow['invoice_id'];
                $customerInvoiceRow = CustomerInvoice::where(['id' => $invoiceId])->first()->toArray();
                $list1 = [
                    [
                        'leftLabelValue' => '账户名称',
                        'rightLabelValue' => $customerInvoiceRow['account_name'],
                    ],
                    [
                        'leftLabelValue' => '纳税人识别号',
                        'rightLabelValue' => $customerInvoiceRow['taxpayer_number'],
                    ],
                    [
                        'leftLabelValue' => '省市区',
                        'rightLabelValue' => $customerInvoiceRow['province_name'] . $customerInvoiceRow['city_name'] . $customerInvoiceRow['area_name'],
                    ],
                    [
                        'leftLabelValue' => '详细地址',
                        'rightLabelValue' => $customerInvoiceRow['address'],
                    ],
                    [
                        'leftLabelValue' => '电话',
                        'rightLabelValue' => $customerInvoiceRow['telphone'],
                    ],
                    [
                        'leftLabelValue' => '开户行',
                        'rightLabelValue' => $customerInvoiceRow['opening_bank'],
                    ],
                    [
                        'leftLabelValue' => '银行卡号',
                        'rightLabelValue' => $customerInvoiceRow['bank_card_number'],
                    ],
                ];

            }

            $list2 = [
                [
                    'leftLabelValue' => '金额',
                    'rightLabelValue' => $customerOrderBillingRow['money'],
                ],
                [
                    'leftLabelValue' => '开户银行',
                    'rightLabelValue' => $customerOrderBillingRow['bank'],
                ],
                [
                    'leftLabelValue' => '支付方式',
                    'rightLabelValue' => $customerOrderBillingRow['pay_type'],
                ],
                [
                    'leftLabelValue' => '收款日期',
                    'rightLabelValue' => $customerOrderBillingRow['collection_days'],
                ],
            ];

            $list = array_merge($list1, $list2);


            $listAll[] = [
                'titleLabelValue' => '开票信息',
                'list' => $list,
                'listImageList' => $listImageList,
            ];
        }

        $returnApe = [
            'imageList' => $imageList,
            'listAll' => $listAll,
        ];

        $maxLen = 20;//设置最大字数长度，如果超过这个值，只能单栏显示
        $middleLen = 10;//设置中等长度，如果超过这个值，但不超过最大值，两栏显示
        $preFiledArr = [
            'num' => 0,//数量
            'minLen' => [],//短字段
            'minddleLen' => [],//中等长度字段
            'mix' => [],//混合
        ];//存放需要组队的字段


        $html = '
        <!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>工序单</title>
    
    <style> /* 清楚默认样式  */
        *{margin:0;padding:0}
        li{list-style:none}
        img{vertical-align:top;border:none}
        body, h1, h2, h3, h4, h5, h6, hr, p, blockquote, /* structural elements 结构元素 */
        dl, dt, dd, ul, ol, li, /* list elements 列表元素 */
        pre, /* text formatting elements 文本格式元素 */
        fieldset, lengend, button, input, textarea, /* form elements 表单元素 */
        th, td { /* table elements 表格元素 */
            margin: 0;
            padding: 0;
        }
        /* 设置默认字体 */
        body,
        button, input, select, textarea { /* for ie */
            /*font: 12px/1 Tahoma, Helvetica, Arial, "宋体", sans-serif;*/
            font: 12px/1 Tahoma, Helvetica, Arial, "\5b8b\4f53", sans-serif; /* 用 ascii 字符表示，使得在任何编码下都无问题 */
        }
        h1 { font-size: 18px; /* 18px / 12px = 1.5 */ }
        h2 { font-size: 16px; }
        h3 { font-size: 14px; }
        h4, h5, h6 { font-size: 100%; }
        address, cite, dfn, em, var { font-style: normal; } /* 将斜体扶正 */
        code, kbd, pre, samp, tt { font-family: "Courier New", Courier, monospace; } /* 统一等宽字体 */
        small { font-size: 12px; } /* 小于 12px 的中文很难阅读，让 small 正常化 */
        /* 重置列表元素 */
        ul, ol { list-style: none; }
        /* 重置文本格式元素 */
        a { text-decoration: none; }
        a:hover { text-decoration: underline; }
        abbr[title], acronym[title] { /* 注：1.ie6 不支持 abbr; 2.这里用了属性选择符，ie6 下无效果 */
            border-bottom: 1px dotted;
            cursor: help;
        }
        q:before, q:after { content: \'\'; }
        /* 重置表单元素 */
        legend { color: #000; } /* for ie6 */
        fieldset, img { border: none; } /* img 搭车：让链接里的 img 无边框 */
        /* 注：optgroup 无法扶正 */
        button, input, select, textarea {
            font-size: 100%; /* 使得表单元素在 ie 下能继承字体大小 */
        }
        /* 重置表格元素 */
        table {
            border-collapse: collapse;
            border-spacing: 0;
        }
        /* 重置 hr */
        hr {
            border: none;
            height: 1px;
        }
    </style>
    <style>
        .nav-left{
            width:35%;
            float: left;
            height:100vh;
        }
        body{
            height: 100vh;
        }
        .nav-right{
            width:60%;
            float: right;
            height:100%;
            padding-right: 50px;
            box-sizing: border-box;
        }
        .nav-right-header-title{
            font-size: 30px;
            font-weight:800;
            padding: 0 10px ;
            line-height: 40px;
        }
        .nav-right-header-box>div{
            width:50%;
            float: left;
            line-height: 30px;
            padding: 0 10px ;
            font-size: 14px;
            box-sizing: border-box;
        }
        .nav-right-header-box{
            overflow: hidden;
            border-bottom: 1px solid #000000;

        }
        .table-title{
            font-size: 20px;
            line-height: 35px;
            font-weight:800;
        }
        .nav-right-table{
            margin-top: 20px;

        }
        .nav-right-table table{
            width:100%;
            border-top:1px solid #000000;
            border-left:1px solid #000000;
            table-layout:fixed;word-break:break-all;
        }
        .nav-right-table td{
            padding: 8px;
            font-size: 14px;
            border-bottom:1px solid #000000;
            border-right:1px solid #000000;
            overflow: hidden;
            white-space:nowrap;
            text-overflow:ellipsis;
         //文本不换行，这样超出一行的部分被截取，显示...
        }
        .nav-right-table .title{
            margin-right: 8px;
        }
        .nav-right-table .value{
            font-weight:800;

        }
        .table-tr2 td{
            width:50%;
        }
        .table-tr1 td{
            width:100%;
        }
        .table-tr3 td{
            width:33.333%;
        }
        .nav-left img{
            width:40%;
            height: auto;
            margin-right:5%;
        }
        .nav-left {
            padding: 20px;
            box-sizing: border-box;
        }
    </style>
</head>
<body>
<div class="body">
        ';
        //添加图片
        $html .= '<div class="nav-left">';

        foreach ($imageList as $k => $imageUrl) {
            if ($k > 2) {
                break;
            }
            $html .= '<img src="' . $imageUrl . '" alt="" style=" width:40%;height:auto;margin-right:5%;">';
        }

        $html .= '</div>';

        $html .= "<div class=\"nav-right\">
            <div class=\"nav-right-header\">
                <div class=\"nav-right-header-title\">{$companyName}生产工序单</div>
                <div class=\"nav-right-header-box\">
                    <div>下单人:{$customerName}
                    </div>
                    <div>生产单号:{$orderInfo['order_title']}
                    </div>
                </div>
            </div>";

        foreach ($listAll as $processList) {
            $html .= "<div class=\"nav-right-table nav-right-table\">
                <div class=\"table-title\">{$processList['titleLabelValue']}</div>
                <table>";
            foreach ($processList['list'] as $tmpRow) {
                $tmpStrLen = mb_strlen($tmpRow['leftLabelValue']) + mb_strlen($tmpRow['rightLabelValue']);
                if ($tmpStrLen > $maxLen) {//如果当前字段为长字段
                    if ($preFiledArr['num'] == 1) {//之前的字段数量为1的情况
                        $html .= "<tr><td colspan='6'>{$preFiledArr['mix'][0]['leftLabelValue']}:{$preFiledArr['mix'][0]['rightLabelValue']}}</td></tr>";

                        //清空之前的字段暂存组
                        $preFiledArr = [
                            'num' => 0,//数量
                            'minLen' => [],//短字段
                            'minddleLen' => [],//中等长度字段
                            'mix' => [],//混合
                        ];
                    } elseif ($preFiledArr['num'] == 2) {//之前的字段数量为2的情况
                        $html .= "<tr class=\"table-tr2\">";
                        $html .= "<td colspan='3'><span class=\"title\">{$preFiledArr['mix'][0]['leftLabelValue']}</span><span class=\"value\">{$preFiledArr['mix'][0]['rightLabelValue']}</span></td>";
                        $html .= "<td colspan='3'><span class=\"title\">{$preFiledArr['mix'][1]['leftLabelValue']}</span><span class=\"value\">{$preFiledArr['mix'][1]['rightLabelValue']}</span></td>";
                        $html .= "</tr>";

                        //清空之前的字段暂存组
                        $preFiledArr = [
                            'num' => 0,//数量
                            'minLen' => [],//短字段
                            'minddleLen' => [],//中等长度字段
                            'mix' => [],//混合
                        ];
                    }
                    //赋值本字段
                    $html .= "<tr class=\"table-tr1\">
                    <td colspan='6'><span class=\"title\">{$tmpRow['leftLabelValue']}</span><span class=\"value\">{$tmpRow['rightLabelValue']}</span></td>
                    </tr>";
                } elseif ($tmpStrLen > $middleLen) {//如果当前字段为中字段
                    if ($preFiledArr['num'] == 1) {//之前的字段数量为1的情况
                        $html .= "<tr class=\"table-tr2\">";
                        $html .= "<td colspan='3'><span class=\"title\">{$preFiledArr['mix'][0]['leftLabelValue']}</span><span class=\"value\">{$preFiledArr['mix'][0]['rightLabelValue']}</span></td>";
                        $html .= "<td colspan='3'><span class=\"title\">{$tmpRow['leftLabelValue']}</span><span class=\"value\">{$tmpRow['rightLabelValue']}</span></td>";
                        $html .= "</tr>";

                        //清空之前的字段暂存组
                        $preFiledArr = [
                            'num' => 0,//数量
                            'minLen' => [],//短字段
                            'minddleLen' => [],//中等长度字段
                            'mix' => [],//混合
                        ];
                    } elseif ($preFiledArr['num'] == 2) {//之前的字段数量为1的情况
                        $html .= "<tr class=\"table-tr2\">";
                        $html .= "<td colspan='3'><span class=\"title\">{$preFiledArr['mix'][0]['leftLabelValue']}</span><span class=\"value\">{$preFiledArr['mix'][0]['rightLabelValue']}</span></td>";
                        $html .= "<td colspan='3'><span class=\"title\">{$preFiledArr['mix'][1]['leftLabelValue']}</span><span class=\"value\">{$preFiledArr['mix'][1]['rightLabelValue']}</span></td>";
                        $html .= "</tr>";


                        //清空之前的字段暂存组&把当前字段存入数组
                        $preFiledArr = [
                            'num' => 1,//数量
                            'minLen' => [],//短字段
                            'minddleLen' => [$tmpRow],//中等长度字段
                            'mix' => [$tmpRow],//混合
                        ];
                    } else {
                        //把当前字段存入数组
                        $preFiledArr = [
                            'num' => 1,//数量
                            'minLen' => [],//短字段
                            'minddleLen' => [$tmpRow],//中等长度字段
                            'mix' => [$tmpRow],//混合
                        ];
                    }
                } else {//如果当前字段为短字段
                    if ($preFiledArr['num'] == 2) {//之前的字段数量为2的情况
                        $html .= "<tr class=\"table-tr3\">";
                        $html .= "<td colspan='2'><span class=\"title\">{$preFiledArr['mix'][0]['leftLabelValue']}</span><span class=\"value\">{$preFiledArr['mix'][0]['rightLabelValue']}</span></td>";
                        $html .= "<td colspan='2'><span class=\"title\">{$preFiledArr['mix'][1]['leftLabelValue']}</span><span class=\"value\">{$preFiledArr['mix'][1]['rightLabelValue']}</span></td>";
                        $html .= "<td colspan='2'><span class=\"title\">{$tmpRow['leftLabelValue']}</span><span class=\"value\">{$tmpRow['rightLabelValue']}</span></td>";
                        $html .= "</tr>";

                        //清空之前的字段暂存组
                        $preFiledArr = [
                            'num' => 0,//数量
                            'minLen' => [],//短字段
                            'minddleLen' => [],//中等长度字段
                            'mix' => [],//混合
                        ];
                    } elseif ($preFiledArr['num'] == 1) {//之前的字段数量为1的情况
                        if (!empty($preFiledArr['minddleLen'])) {//之前的字段组里存的是中字段
                            $html .= "<tr class=\"table-tr2\">";
                            $html .= "<td colspan='3'><span class=\"title\">{$preFiledArr['mix'][0]['leftLabelValue']}</span><span class=\"value\">{$preFiledArr['mix'][0]['rightLabelValue']}</span></td>";
                            $html .= "<td colspan='3'><span class=\"title\">{$tmpRow['leftLabelValue']}</span><span class=\"value\">{$tmpRow['rightLabelValue']}</span></td>";
                            $html .= "</tr>";

                            //清空之前的字段暂存组
                            $preFiledArr = [
                                'num' => 0,//数量
                                'minLen' => [],//短字段
                                'minddleLen' => [],//中等长度字段
                                'mix' => [],//混合
                            ];
                        } else {//之前的字段组里存的是短字段
                            $preFiledArr['num']++;
                            $preFiledArr['minLen'][] = $tmpRow;
                            $preFiledArr['mix'][] = $tmpRow;
                        }

                    } else {//之前的字段组为空
                        $preFiledArr = [
                            'num' => 1,//数量
                            'minLen' => [$tmpRow],//短字段
                            'minddleLen' => [],//中等长度字段
                            'mix' => [$tmpRow],//混合
                        ];
                    }
                }
            }

            $html .= "</table>
            </div>";
        }

//        echo $html;die();


        $mpdf = new \Mpdf\Mpdf([
            'mode' => 'utf-8',
            'format' => [600, 250],
        ]);
        $mpdf->list_indent_first_level = 0;
        $mpdf->SetDisplayMode('fullpage');
        $mpdf->useAdobeCJK = TRUE;
        $mpdf->autoScriptToLang = true;
        $mpdf->autoLangToFont = true;
        $mpdf->WriteHTML($html);


        //创建文件夹
        $pdfDir = 'pdf/' . date('Ymd');
        if (!file_exists('../storage/upload/' . $pdfDir)) {
            \Storage::makeDirectory($pdfDir);
        }

        $pdfFilePath = $pdfDir . '/' . $orderInfo['order_title'] . '.pdf';
        $outputFileName = '../storage/upload/' . $pdfFilePath;
//        $mpdf->Output($outputFileName);
        $mpdf->Output();
//        $trueUrl = \Storage::url($pdfFilePath);
//        header('Location:'.$trueUrl);

        die();
    }

    //员工成品入库
    public function employeeFinishedProduct()
    {
        $userId = Func::getHeaderValueByName('userid');
        $userInfo = DepartmentUser::getCurrentInfo($userId)->toArray();

        $orderProcessCourseId = request('order_process_course_id');
        $orderProcessCourseRow = \App\Eloquent\Ygt\OrderProcessCourse::where(['id' => $orderProcessCourseId])->first();
        $orderProcessRow = \App\Eloquent\Ygt\OrderProcess::where(['id' => $orderProcessCourseRow['order_process_id']])->first();
        $orderId = $orderProcessRow['order_id'];


        $userId = $userId;
        $orderId = $orderId;
        $finishNumber = $orderProcessCourseRow['finish_number'];


        if (!$finishNumber) {
            return [
                'code' => 1,
                'message' => '您还未提交完成数量'
            ];
        }

        //已提交数量
        $finishedProductNum = $orderProcessCourseRow['finished_product_num'];
        $curSubmitNum = $finishNumber - $finishedProductNum;
        if ($curSubmitNum <= 0) {
            return [
                'code' => 2,
                'message' => '没有新的完成数量需要入库'
            ];
        }


        //调整，先临时保存
//        \App\Engine\WarehouseEngine::insertOneData($userId, $orderId, $curSubmitNum);

        $tmpObj = \App\Eloquent\Ygt\OrderFinishedProduct::firstOrNew(['id'=>'']);
        $tmpInsertRow = [
            'order_id' => $orderId,
            'order_process_id' => $orderProcessRow['id'],
            'order_process_course_id' => $orderProcessCourseId,
            'number' => $curSubmitNum,
            'uid' => $userId,
            'company_id' => $userInfo['company_id'],
            'status' => 1,
        ];
        $tmpObj->fill($tmpInsertRow);
        $tmpObj->save();
        $orderFinishedProductId = $tmpObj->id;




        //修改已提交值
        $orderProcessCourseRow->finished_product_num = $finishNumber;
        $orderProcessCourseRow->save();

        //发送消息给发货员 zhuyujun 20180726 || 改为给仓管发消息，仓管入库时再给发货员发消息
        $companyId = $orderProcessCourseRow['company_id'];
        $orderRow = \App\Eloquent\Ygt\Order::where(['id' => $orderId])->first();
        $foreignKey = $orderRow['customer_order_id'];
        $privilegeIdList = \App\Engine\OrderEngine::getPrivilegeByNode($companyId, 7);

        //获取工艺单位
        $curProcessRow = \App\Eloquent\Ygt\Process::getInfo(['id' => $orderProcessRow['process_type']])->toArray();
        if($curProcessRow['measurement_unit']){
            $curProcessMeasurementUnit = $curProcessRow['measurement_unit'];
        }else{
            $curProcessMeasurementUnit = '';
        }

//        内容：工单号、品名、成品入库数量
        $tmpOrderTitle = \App\Engine\Common::changeSnCode($orderRow['order_title']);
        $tmpProductName = \App\Engine\OrderEngine::getOrderFiledValueTrue($orderRow['product_name'], 20);//品名
        $messageContent = "工单号:{$tmpOrderTitle}rnrn";
        $messageContent .= "品名:{$tmpProductName}rnrn";
        $messageContent .= "成品入库数量:{$curSubmitNum}{$curProcessMeasurementUnit}rnrn";

        foreach ($privilegeIdList as $privilegeId) {
            if ($privilegeId) {
                $data = [
                    'company_id' => $companyId,
                    'privilege_id' => $privilegeId,
                    'form_user_id' => $userId,
                    'to_user_id' => '',
                    'foreign_key' => $foreignKey,
                    'type' => 42,//跳转到成品验收入库界面
                    'type_id' => $orderFinishedProductId,
                    'title' => $orderRow['order_title'],
                    'content' => $messageContent,
                    'theme' => '工单成品入库',
                ];
                UserMessage::sendCustomerOrderMessage($data);
            }
        }


        return '操作成功';
    }

    //工单相关材料详情页面
    public function getOrderMaterialDetail()
    {

        $userId = Func::getHeaderValueByName('userid');
        $userInfo = DepartmentUser::getCurrentInfo($userId)->toArray();
        $companyId = $userInfo['company_id'];

        $orderId = request('order_id');
        $waitPurchaseId = request('wait_purchase_id');


        //优先去待采购ID
        if($waitPurchaseId){
            $orderId = \App\Eloquent\Ygt\WaitPurchase::where(['id'=>$waitPurchaseId])->first()->order_id;
            //获取工单详情
            $orderRow = \App\Eloquent\Ygt\Order::where(['id' => $orderId])->first();
            $materialIdList = \App\Eloquent\Ygt\WaitPurchaseMaterial::where(['wait_purchase_id' => $waitPurchaseId])->get()->pluck('material_id');
        }else{
            //获取工单详情
            $orderRow = \App\Eloquent\Ygt\Order::where(['id' => $orderId])->first();
            //获取工单相关的所有材料详情
            $materialIdList = \App\Eloquent\Ygt\OrderMaterial::where(['order_id' => $orderId])->get()->pluck('material_id');
        }

        //获取材料详情
        $materialList = [];
        foreach ($materialIdList as $materialId){
            if(strstr($materialId,'A')){
                $tmpAssemblageMaterialId = str_replace('A','',$materialId);
                $tmpMaterialRow = \App\Eloquent\Ygt\AssemblageMaterial::where(['id'=>$tmpAssemblageMaterialId])->first();
                if(!empty($tmpMaterialRow)){
                    $tmpMaterialRow['is_assemblage'] = 1;
                }else{
                    continue;
                }

            }else{
                $tmpMaterialRow = \App\Eloquent\Ygt\Product::where(['id'=>$materialId])->first();
                if(!empty($tmpMaterialRow)){
                    $tmpMaterialRow['is_assemblage'] = 0;
                }else{
                    //兼容软删除
                    $tmpMaterialRow = \App\Eloquent\Ygt\Product::withTrashed()->where(['id'=>$materialId])->first();



                    if(!empty($tmpMaterialRow)) {
                        $tmpMaterialRow['product_name'] = $tmpMaterialRow['product_name']."【已删除】";
                        $tmpMaterialRow['is_assemblage'] = 0;
                    }else{
                        continue;
                    }
                }
            }

            if(!empty($materialList)){
                $materialList = $materialList->merge([$tmpMaterialRow]);
            }else{
                $materialList = collect([$tmpMaterialRow]);
            }
        }

//        $materialList = \App\Eloquent\Ygt\Product::whereIn('id', $materialIdList)->get();

        //添加图片地址
        if(!empty($materialList)){
            $materialList = $materialList->map(function ($item) {
                $imgId = $item['img_id'];
                if ($imgId) {
                    $exampleImg = ImgUpload::getImgUrlById($imgId, false);
                    $item['img_url'] = $exampleImg;
                }

                $item['purchase_number'] = '';

                return $item;
            });

            $materialList = \App\Engine\Product::composeList($materialList);
        }

        //处理图片数据
        $imgIdList = explode(',', $orderRow['production_case_diagram']);
        $exampleImg = '';
        $imgNum = 0;
        foreach ($imgIdList as $imgId) {
            if (!trim($imgId)) {//过滤空格 图片id应该不会有0
                continue;
            }
            $imgNum++;
            if (!$exampleImg) {//取第一张图作为示例图
                $exampleImg = ImgUpload::getImgUrlById($imgId);
            }
        }

        //获取工序类型名称
        $orderTypeTitle = \App\Engine\OrderType::getOneValueById($orderRow['order_type'], 'title');

        //新增返回参数，是否允许创建采购申请
        $isAblePurchase = 0;
        //采购员权限的用户
        $privilegeIdList = \App\Engine\OrderEngine::getPrivilegeByNode($companyId, 10);
        if (in_array($userInfo['privilege_id'], $privilegeIdList)) {

            //如果已经创建过采购，限制二次采购
            if(WaitPurchase::where('order_id','=',$orderId)->where('status','=',1)->count()){
                $isAblePurchase = 1;
            }
//            $tmpPurchaseObj = \App\Eloquent\Ygt\Purchase::where(['order_id'=>$orderId])->first();
//            if(!$tmpPurchaseObj){
//                $isAblePurchase = 1;
//            }
        }

        //新增下单数量 20180821 zhuyujun
        $orderNum = '';
        if($orderRow['product_num']){
            $orderNumArr = explode(',',$orderRow['product_num']);
            if(isset($orderNumArr[0]) && isset($orderNumArr[1])){
                if(!$orderNumArr[0]){
                    $orderNumArr[0] = '';
                }
                $orderNumArr = $orderNumArr[0].$orderNumArr[1];
            }
        }

        //修改集合材料的ID
        if(!empty($materialList)){
            $materialList = $materialList->toArray();
        }else{
            $materialList = [];
        }

        //获取优选采购的材料id
        $recommendMaterialIdArr = OrderMaterialPurchaseMark::where('order_id','=',$orderId)->where('is_purchase','=',1)->pluck('material_id')->toArray();
        foreach ($materialList as $key => $materialRow){
            if($materialRow['is_assemblage']){
                $materialList[$key]['id'] = "A".$materialRow['id'];
            }

            if(in_array($materialList[$key]['id'],$recommendMaterialIdArr)){
                $materialList[$key]['is_purchase'] = 1;
            }
            else{
                $materialList[$key]['is_purchase'] = 0;
            }
        }

        $re = [
            'productImage' => $exampleImg,
            'orderTypeTitle' => $orderTypeTitle,
            'productOrderValue' => '工单号:' . $orderRow['order_title'],
            'orderId' => $orderRow['id'],
            'finishDate' =>$orderRow['finished_date']." ".$orderNumArr,//新增下单数量 20180821 zhuyujun
            'imgTitle' => '共' . $imgNum . '张图片',//示例图文字提示
            'isAblePurchase' => $isAblePurchase,//是否允许创建采购申请 1-允许 0-禁止
            'materialList' => $materialList,
        ];//接口返回的值


        return $re;
    }


    //工序管理员领取材料界面
    public function orderProcessManageReceiveMaterial(Request $request)
    {
        //获取传入数据
        $input = $request->all();
        $input['order_process_id'] = isset($input['order_process_id']) ? $input['order_process_id'] : '';
        $input['order_process_course_id'] = isset($input['order_process_course_id']) ? $input['order_process_course_id'] : '';


        //取第一个员工工单的ID，作为领材员工（兼容之前的逻辑）
        $orderProcessCourseId = '';
        $orderProcessCourseRow = \App\Eloquent\Ygt\OrderProcessCourse::where(['order_process_id' => $input['order_process_id']])->first();


        if ($orderProcessCourseRow) {
            $orderProcessCourseId = $orderProcessCourseRow['id'];
        }

        //获取对应工序信息
        $orderProcessInfo = OrderProcess::where('id', $input['order_process_id'])->first()->toArray();
        //获取工单信息
        $orderInfo = Order::where('id', $orderProcessInfo['order_id'])->first()->toArray();
        //2019-01-23 Linwei
        $customer_id_current_order = $orderInfo['customer_name'];
        //获取工序名称
        $processTitle = Process::getOneValueById($orderProcessInfo['process_type'], 'title');

        //如果工序有材料但还未自动导入到员工材料表，需要导入到员工材料表
        $orderMaterialList = \App\Eloquent\Ygt\OrderMaterial::where(['order_process_id' => $input['order_process_id']])->get()->toArray();
        if (!empty($orderMaterialList)) {
            //判断员工材料表是否有数据
            $orderMaterialCourseCount = \App\Eloquent\Ygt\OrderMaterialCourse::where(['order_process_course_id' => $orderProcessCourseId, 'process_type' => $orderProcessInfo['process_type']])->count();
            if (!$orderMaterialCourseCount) {
                foreach ($orderMaterialList as $orderMaterialRow) {
                    $orderMaterialCourse = OrderMaterialCourse::firstOrNew(['id' => '']);
                    unset($orderMaterialRow['order_id']);
                    unset($orderMaterialRow['uid']);
                    unset($orderMaterialRow['price']);
                    $orderMaterialRow['order_process_course_id'] = $orderProcessCourseId;
                    $orderMaterialCourse->fill($orderMaterialRow);
                    $orderMaterialCourse->save();
                }
            }
        }


        //获取工单创建时设置的材料
//        $fields = [
//            'ygt_order_material_course.*',
//            'ygt_product.product_name',
//            'ygt_product.unit',
//            'ygt_product.number',
//        ];
//        $orderMaterialCollection = OrderMaterialCourse::where(['order_process_course_id' => $orderProcessCourseId, 'process_type' => $orderProcessInfo['process_type']])->leftJoin('ygt_product', 'ygt_order_material_course.material_id', '=', 'ygt_product.id')->select($fields)->orderBy('ygt_order_material_course.allow_delete','asc')->get();
        $orderMaterialCollection = OrderMaterialCourse::where(['order_process_course_id' => $orderProcessCourseId, 'process_type' => $orderProcessInfo['process_type']])->orderBy('ygt_order_material_course.allow_delete','asc')->get();

        $orderMaterialList = [];
        foreach ($orderMaterialCollection as $tmpRow) {
            $tmpOrderMaterialRow = $tmpRow->toArray();

            //添加分次领取记录
            $receiveGradationList = [];
            $orderMaterialReceiveGradationList = \App\Eloquent\Ygt\OrderMaterialReceiveGradation::where(['order_process_course_id'=>$orderProcessCourseId,'material_id'=>$tmpOrderMaterialRow['material_id']])->get();
            if($orderMaterialReceiveGradationList){
                $orderMaterialReceiveGradationList = $orderMaterialReceiveGradationList->toArray();
                foreach ($orderMaterialReceiveGradationList as $tmpKey => $tmpRow){
                    $receiveGradationList[] = [
                        'num' => $tmpRow['num'],//领取数量
                        'receive_time' => date('Y-m-d',$tmpRow['created_at']),//领取时间
                    ];
                }
            }

            $tmpOrderMaterialRow['receive_gradation'] = $receiveGradationList;

//            $tmpMateriaRow = ProductEngine::getProductInfoExist($tmpOrderMaterialRow['material_id']);
            //考虑集合材料的问题
            if(strstr($tmpOrderMaterialRow['material_id'],'A')){
                $tmpAssemblageMaterialId = str_replace('A','',$tmpOrderMaterialRow['material_id']);
                $tmpMateriaRow = \App\Eloquent\Ygt\AssemblageMaterial::where(['id'=>$tmpAssemblageMaterialId])->first();
            }else{
                $tmpMateriaRow = ProductEngine::getProductInfo($tmpOrderMaterialRow['material_id']);
            }



            if ($tmpMateriaRow) {
                $tmpOrderMaterialRow['product_no'] = $tmpMateriaRow['product_no'];
                $tmpOrderMaterialRow['is_trash'] = 0;
                if(!$tmpMateriaRow['number']){
                    $tmpMateriaRow['number'] = 0;
                }

                $tmpOrderMaterialRow['product_name'] = $tmpMateriaRow['product_name'];// . "[库存{$tmpMateriaRow['number']}{$tmpMateriaRow['unit']}]";
            } else {
                //删除材料处理
//                $tmpMateriaRow = ProductEngine::getProductInfoTrash($tmpOrderMaterialRow['material_id']);
                //考虑集合材料的问题
                if(strstr($tmpOrderMaterialRow['material_id'],'A')){
                    $tmpAssemblageMaterialId = str_replace('A','',$tmpOrderMaterialRow['material_id']);
                    $tmpMateriaRow = \App\Eloquent\Ygt\AssemblageMaterial::withTrashed()->where(['id'=>$tmpAssemblageMaterialId])->first();
                }else{
                    $tmpMateriaRow = ProductEngine::getProductInfo($tmpOrderMaterialRow['material_id']);
                }

                $tmpOrderMaterialRow['is_trash'] = 1;
                $tmpOrderMaterialRow['product_name'] = $tmpMateriaRow['product_name'] . "[材料已删除]";
            }


            //添加领取总数量信息
            if($tmpOrderMaterialRow['receive_number']){
                $tmpOrderMaterialRow['receive_number_all'] = "累计{$tmpOrderMaterialRow['receive_number']}{$tmpMateriaRow['unit']}";
            }else{
                $tmpOrderMaterialRow['receive_number'] = 0;
                $tmpOrderMaterialRow['receive_number_all'] = "累计{$tmpOrderMaterialRow['receive_number']}{$tmpMateriaRow['unit']}";
            }

            //追加信息 所有权、供应商、属性
            //子材料
            if(isset($tmpMateriaRow['assemblage_material_id'])){
                $tmpOrderMaterialRow['customer_name'] = Customer::getOneValueById($tmpMateriaRow['customer_id'],'customer_name');
                $tmpOrderMaterialRow['supplier_name'] = SellerCompany::getOneValueById($tmpMateriaRow['seller_company_id'],'title');
                $tmpOrderMaterialRow['attr_list'] = \App\Engine\Material::getMaterialField($tmpMateriaRow['assemblage_material_id']);
                $tmpOrderMaterialRow['custom_fields_text'] = $tmpOrderMaterialRow['attr_list']['custom_fields_text'];
                $tmpOrderMaterialRow['img_url'] = ImgUpload::getImgUrlById($tmpMateriaRow['img_id']);;
                $tmpOrderMaterialRow['number'] = $tmpMateriaRow['number'];
                $tmpOrderMaterialRow['unit'] = $tmpMateriaRow['unit'];

                $warningNumber   = $tmpMateriaRow['warning_number'];
                $valNumber       = $tmpMateriaRow['number'];
                $isWarning       = ($warningNumber > $valNumber ? 1 : 0);
                //我也不知道这是什么鬼逻辑
                if($valNumber > $warningNumber){
                    $circleFrontColor    ='#00AAEE';
                    $circleBackColor     ='#E4F6FD';
                }else if($valNumber > 0){
                    $circleFrontColor    ='#FFF7E4';
                    $circleBackColor     ='#FFB401';
                }else{
                    $circleFrontColor    ='#FF5252';
                    $circleBackColor     ='#FFEDED';
                }
                //百分百
                $valFullNumber   = $tmpMateriaRow['full_number'];
                $ratio           = 0;
                if($valFullNumber > 0)
                {
                    $ratio       = round(($valNumber/$valFullNumber)*100);
                }

                $tmpOrderMaterialRow['ratio'] = $ratio;

                $tmpOrderMaterialRow['circle_back_color'] = $circleFrontColor;
                $tmpOrderMaterialRow['circle_front_color'] = $circleBackColor;

                $orderMaterialList[] = $tmpOrderMaterialRow;
//                , , , , circle_back_color, circle_front_color, ratio
            }
            //集合材料
            else{
//                $tmpOrderMaterialRow['customer_name'] = '';
                //$tmpOrderMaterialRow['supplier_name'] = '不限'.'-'.$tmpAssemblageMaterialId;
//                $tmpOrderMaterialRow['attr_list'] = \App\Engine\Material::getMaterialField($tmpMateriaRow['id']);
//                $tmpOrderMaterialRow['custom_fields_text'] = $tmpOrderMaterialRow['attr_list']['custom_fields_text'];
//

                //2019-01-23 Linwei  把不限的材料列表都显示出来
                $tmpAssemblageMaterialId = str_replace('A','',$tmpOrderMaterialRow['material_id']);
                $tmpMaterialCollection = \App\Eloquent\Ygt\Product::where(['assemblage_material_id'=>$tmpAssemblageMaterialId])->whereIn('customer_id',[0,$customer_id_current_order])->get();
                    //select product_name,assemblage_material_id,customer_id from ygt_product where assemblage_material_id in (846,2282,2283)

                foreach ($tmpMaterialCollection as $tmpMTRow) {
                    $tmpOrderMaterialRow['customer_name'] = Customer::getOneValueById($tmpMTRow['customer_id'],'customer_name');
                    $tmpOrderMaterialRow['supplier_name'] = SellerCompany::getOneValueById($tmpMTRow['seller_company_id'],'title');
                    $tmpOrderMaterialRow['attr_list'] = \App\Engine\Material::getMaterialField($tmpMTRow['assemblage_material_id']);
                    $tmpOrderMaterialRow['custom_fields_text'] = $tmpOrderMaterialRow['attr_list']['custom_fields_text'];
                    $tmpOrderMaterialRow['img_url'] = ImgUpload::getImgUrlById($tmpMTRow['img_id']);;
                    $tmpOrderMaterialRow['number'] = $tmpMTRow['number'];
                    $tmpOrderMaterialRow['unit'] = $tmpMTRow['unit'];

                    $warningNumber   = $tmpMTRow['warning_number'];
                    $valNumber       = $tmpMTRow['number'];
                    $isWarning       = ($warningNumber > $valNumber ? 1 : 0);
                    //我也不知道这是什么鬼逻辑
                    if($valNumber > $warningNumber){
                        $circleFrontColor    ='#00AAEE';
                        $circleBackColor     ='#E4F6FD';
                    }else if($valNumber > 0){
                        $circleFrontColor    ='#FFF7E4';
                        $circleBackColor     ='#FFB401';
                    }else{
                        $circleFrontColor    ='#FF5252';
                        $circleBackColor     ='#FFEDED';
                    }
                    //百分百
                    $valFullNumber   = $tmpMTRow['full_number'];
                    $ratio           = 0;
                    if($valFullNumber > 0)
                    {
                        $ratio       = round(($valNumber/$valFullNumber)*100);
                    }

                    $tmpOrderMaterialRow['ratio'] = $ratio;

                    $tmpOrderMaterialRow['circle_back_color'] = $circleFrontColor;
                    $tmpOrderMaterialRow['circle_front_color'] = $circleBackColor;
                    $orderMaterialList[] = $tmpOrderMaterialRow;
                }
            }

            //2019-0123 分别加到上面的if else 中
            //$orderMaterialList[] = $tmpOrderMaterialRow;

        }

        //处理图片数据
        $imgIdList = explode(',', $orderInfo['production_case_diagram']);
        $exampleImg = '';
        $imgNum = 0;
        foreach ($imgIdList as $imgId) {
            if (!trim($imgId)) {//过滤空格 图片id应该不会有0
                continue;
            }
            $imgNum++;
            if (!$exampleImg) {//取第一张图作为示例图
                $exampleImg = ImgUpload::getImgUrlById($imgId);
            }
        }

        //获取上一个部门&上一个部门
        $preProcessList = OrderType::getAllPrevOrderProcess($orderInfo['order_type'], $orderProcessInfo['process_type'])->toArray();
        //获取预估完成时间最晚的一个，待开工的部门优先级最高
        $preProcess = '';//上一个工序（部门）
        $preProcessEstimatedTime = 0;
        $preProcessEstimatedTimeStr = '';
        $lastOrderProcessId = 0;
        $finishNum = 0;
        $preProcessMeasurementUnit = '';
        $isPreEmpty = 0;

        if ($preProcessList) {
            foreach ($preProcessList as $processId) {
                //获取工序信息
                $preOrderProcessInfo = OrderProcess::where(['order_id' => $orderInfo['id'], 'process_type' => $processId])->first()->toArray();

                $where = ['id' => $processId];
                $process = Process::getInfo($where)->toArray();
                $preProcess = $process['title'];//工序名称
                $processIsSum = $process['is_sum'];//工序数量是否累加 0-不累加 1-累加
//                $preProcess = Process::getOneValueById($preOrderProcessInfo['process_type'], 'title');
//                $processIsSum = Process::getOneValueById($preOrderProcessInfo['process_type'], 'is_sum');

                $lastOrderProcessId = $preOrderProcessInfo['id'];
                if ($preOrderProcessInfo['status'] == 1) {//待开工
                    $preProcessEstimatedTimeStr = '待开工';
                    break;
                } else {
                    //获取员工工单列表
                    //调整-预计完成时间调整为从员工工单获取
                    $orderProcessCourseList = OrderProcessCourse::where(['order_process_id' => $preOrderProcessInfo['id']])->get();
                    $finishNum = 0;
                    foreach ($orderProcessCourseList as $orderProcessCourseRow) {

                        $tmpPreProcessEstimatedTime = $orderProcessCourseRow['start_time'] + $orderProcessCourseRow['estimated_time_hour'] * 3600 + $orderProcessCourseRow['estimated_time_minute'] * 60;
                        if ($tmpPreProcessEstimatedTime > $preProcessEstimatedTime) {
                            $preProcessEstimatedTime = $tmpPreProcessEstimatedTime;
                            $preProcessEstimatedTimeStr = '' . date('Y年m月d日 H时', $preProcessEstimatedTime);
                        }


                        //设定的角色不进行统计数量到工序数量中
                        //过滤异常数据
                        if (!DepartmentUser::getCurrentInfo($orderProcessCourseRow['uid'])) {
                            continue;
                        }
                        $tmpUserInfo = DepartmentUser::getCurrentInfo($orderProcessCourseRow['uid'])->toArray();
                        $tmpPrivilegeId = $tmpUserInfo['privilege_id'];
                        if (OrderEngine::getProcessNumNoStatistics($tmpPrivilegeId)) {
                            continue;
                        }

                        $finishNum += $orderProcessCourseRow['finish_number'];
                        if (!$processIsSum) {//不累加
                            $tmpUserInfo = DepartmentUser::getCurrentInfo($orderProcessCourseRow['uid'])->toArray();
                            $tmpPrivilegeId = $tmpUserInfo['privilege_id'];
                            if (isset($finishUserNumList[$tmpPrivilegeId])) {
                                $finishUserNumList[$tmpPrivilegeId]['finish_number'] += $orderProcessCourseRow['finish_number'];
                            } else {
                                $finishUserNumList[$tmpPrivilegeId]['finish_number'] = $orderProcessCourseRow['finish_number'];
                            }
                        }
                    }


                    if ($preProcessEstimatedTime < 631152000) {//过滤1970的情况
                        $preProcessEstimatedTimeStr = '';
                    }


                    //不累加--未完工时取完成量最小的员工
                    if (!empty($finishUserNumList)) {
                        $finishMinNum = '';
                        foreach ($finishUserNumList as $finishUserNumRow) {
                            if ($finishMinNum === 0) {//如果有员工完成数量为0，
                                break;
                            }

                            if ($finishUserNumRow['finish_number'] < $finishMinNum || $finishMinNum === '') {//如果有员工完成数量更少，或者第一个员工的数据
                                $finishMinNum = $finishUserNumRow['finish_number'];
                            }
                        }
                        $finishNum = $finishMinNum;
                        $preProcessMeasurementUnit = $process['measurement_unit'];
                    }

                }
            }
        } else {
            $preProcess = '无';//上一个工序（部门）
            $preProcessEstimatedTimeStr = '';
            $isPreEmpty = 1;
        }

        //获取领材是否需要扫码的配置
        $companyId = $orderInfo['company_id'];//厂id
        $isScanCode = Company::isScanCode($companyId);

        //获取工序类型名称
        $orderTypeTitle = OrderType::getOneValueById($orderInfo['order_type'], 'title');
        
        //获取半成品信息
        $orderProcessProductList = [];
        $tmpOrderProcessProductReceiveList = \App\Eloquent\Ygt\OrderProcessProductReceive::where(['order_process_id'=>$orderProcessInfo['id']])->get();
        foreach ($tmpOrderProcessProductReceiveList as $tmpOrderProcessProductReceiveRow){
            //获取半成品详情
            $tmpProcessProductId = $tmpOrderProcessProductReceiveRow['process_product_id'];
            $tmpProcessProductRow = \App\Eloquent\Ygt\ProcessProduct::where(['id'=>$tmpProcessProductId])->first();

            if(!$tmpProcessProductRow['plate_model']){
                $tmpProcessProductRow['plate_model'] = '';
            }

            $circleFrontColor    ='#00AAEE';
            $circleBackColor     ='#E4F6FD';
            $tmpProcessProductRow['circle_front_color']   = $circleFrontColor;
            $tmpProcessProductRow['circle_back_color']    = $circleBackColor;

            //百分百
            $valFullNumber   = $tmpProcessProductRow['in_number'];
            $ratio           = 0;
            if($valFullNumber > 0)
            {
                $ratio       = round(($tmpProcessProductRow['number']/$valFullNumber)*100);
            }
            $tmpProcessProductRow['ratio']        = $ratio;

            $tmpProcessProductRow['img_url'] = '';
            $tmpProcessProductRow['main_material'] = '';
            //获取分次领取记录
            $tmpOrderProcessProductReceiveDetailList = \App\Eloquent\Ygt\OrderProcessProductReceiveDetail::where(['process_product_receive_id'=>$tmpOrderProcessProductReceiveRow['id']])->get();
            $tmpReceiveGradationList = [];
            foreach ($tmpOrderProcessProductReceiveDetailList as $tmpOrderProcessProductReceiveDetailRow){
                $tmpRow = $tmpOrderProcessProductReceiveDetailRow->toArray();
                $tmpReceiveGradationList[] = [
                    'num' => $tmpRow['number'],//领取数量
                    'receive_time' => date('Y-m-d',$tmpRow['created_at']),//领取时间
                ];
            }

            $tmpProcessProductRow['receive_gradation'] = $tmpReceiveGradationList;
            $orderProcessProductList[] = $tmpProcessProductRow;
        }

        $return = [];
        $return['product_name'] = $orderTypeTitle;//产品名称
        $return['order_title'] = $orderInfo['order_title'];//生产单号
        $return['finished_date'] = $orderInfo['finished_date'];//交货日期
        $return['estimated_time'] = $preProcessEstimatedTimeStr;//预计完成
        $return['last_order_process_finish_num'] = $finishNum.$preProcessMeasurementUnit;//上一工序完成数量
        $return['img_url'] = $exampleImg;//示例图
        $return['img_title'] = '共' . $imgNum . '张图片';//示例图文字提示
        $return['last_department'] = $preProcess;//上一部门
        $return['is_pre_empty'] = $isPreEmpty;//1-没有上一工序 0-有
        $return['last_order_process_id'] = $lastOrderProcessId;//上一工序id
        $return['jump_tips'] = '已接单[' . $processTitle . ']';//跳转到工单详情文字提示
        $return['order_material_list'] = $orderMaterialList;//领取材料列表
        $return['order_process_product_list'] = $orderProcessProductList;//领取材料列表
        $return['img_order_id'] = $orderInfo['id'];//主工单id
        $return['is_scan_code'] = $isScanCode;//是否需要扫码领取材料
        $return['order_process_course_id'] = $orderProcessCourseId;//员工工单ID，领材提交和增删材料需要用到

        return $return;
    }

    //工序管理员用料情况界面
    public function orderProcessManageUseMaterial(Request $request)
    {
        $userId = Func::getHeaderValueByName('userid');
        $userInfo = DepartmentUser::getCurrentInfo($userId)->toArray();

        //获取传入数据
        $input = $request->all();
        $input['order_process_id'] = isset($input['order_process_id']) ? $input['order_process_id'] : '';

        //校验参数
        $rules = [
            'order_process_id' => 'required',
        ];
        $messages = [
            'order_process_id.required' => '缺少工单id',
        ];
        $this->validateRequestParameters($input, $rules, true, $messages);


        //获取对应工单工序表信息
        $orderProcessInfo = OrderProcess::where('id', $input['order_process_id'])->first()->toArray();

        //获取工单信息
        $orderInfo = Order::where('id', $orderProcessInfo['order_id'])->first()->toArray();
        //获取工序名称
        $processTitle = Process::getOneValueById($orderProcessInfo['process_type'], 'title');

        //获取工单创建时设置的材料
//        $fields = [
//            'ygt_order_material_course.*',
//            'ygt_product.product_name'
//        ];
//        $orderMaterialCollection = OrderMaterialCourse::where(['order_process_id' => $input['order_process_id']])->leftJoin('ygt_product', 'ygt_order_material_course.material_id', '=', 'ygt_product.id')->select($fields)->get();
        $orderMaterialCollection = OrderMaterialCourse::where(['order_process_id' => $input['order_process_id']])->get();

        //获取第一个员工工单ID用于提交材料
        //取第一个员工工单的ID，作为领材员工（兼容之前的逻辑）
        $orderProcessCourseId = '';
        $orderProcessCourseRow = \App\Eloquent\Ygt\OrderProcessCourse::where(['order_process_id' => $input['order_process_id']])->first();


        if ($orderProcessCourseRow) {
            $orderProcessCourseId = $orderProcessCourseRow['id'];
        }

        $orderMaterialList = [];
        foreach ($orderMaterialCollection as $tmpRow) {
//            $orderProcessCourseId = $tmpRow['order_process_course_id'];
            $tmpOrderMaterialRow = $tmpRow->toArray();
//            $tmpMateriaRow = ProductEngine::getProductInfo($tmpOrderMaterialRow['material_id']);
//            $tmpMateriaRow = ProductEngine::getProductInfoExist($tmpOrderMaterialRow['material_id']);
            //考虑集合材料的问题
            if(strstr($tmpOrderMaterialRow['material_id'],'A')){
                $tmpAssemblageMaterialId = str_replace('A','',$tmpOrderMaterialRow['material_id']);
                $tmpMateriaRow = \App\Eloquent\Ygt\AssemblageMaterial::where(['id'=>$tmpAssemblageMaterialId])->first();
            }else{
                $tmpMateriaRow = ProductEngine::getProductInfo($tmpOrderMaterialRow['material_id']);
            }

            if ($tmpMateriaRow) {
                $tmpOrderMaterialRow['product_no'] = $tmpMateriaRow['product_no'];
                $tmpOrderMaterialRow['is_trash'] = 0;
                $tmpOrderMaterialRow['product_name'] = $tmpMateriaRow['product_name'];
            } else {
                //删除材料处理
//                $tmpMateriaRow = ProductEngine::getProductInfoTrash($tmpOrderMaterialRow['material_id']);
                //考虑集合材料的问题
                if(strstr($tmpOrderMaterialRow['material_id'],'A')){
                    $tmpAssemblageMaterialId = str_replace('A','',$tmpOrderMaterialRow['material_id']);
                    $tmpMateriaRow = \App\Eloquent\Ygt\AssemblageMaterial::withTrashed()->where(['id'=>$tmpAssemblageMaterialId])->first();
                }else{
                    $tmpMateriaRow = ProductEngine::getProductInfo($tmpOrderMaterialRow['material_id']);
                }


                $tmpOrderMaterialRow['is_trash'] = 1;
                $tmpOrderMaterialRow['product_name'] = $tmpMateriaRow['product_name'] . "[材料已删除]";
            }

            if (!$tmpOrderMaterialRow['receive_number']) {
                $tmpOrderMaterialRow['receive_number'] = 0;
            }

            //补齐 供应商 归属人 属性
            if($tmpMateriaRow['customer_id']){
                $tmpOrderMaterialRow['customer_name']= \App\Eloquent\Ygt\Customer::getOneValueById($tmpMateriaRow['customer_id'],'customer_name');
            }

            if($tmpMateriaRow['seller_company_id']){
                $tmpOrderMaterialRow['supplier_name']= \App\Eloquent\Ygt\SellerCompany::getOneValueById($tmpMateriaRow['seller_company_id'],'title');
            }

            if($tmpMateriaRow['assemblage_material_id']){
                $tempAttrList = \App\Engine\Material::getMaterialField($tmpMateriaRow['assemblage_material_id']);
                $tmpOrderMaterialRow['custom_fields_text'] = $tempAttrList['custom_fields_text'];
            }

            if($tmpMateriaRow['img_id']){
                $tmpOrderMaterialRow['img_url'] = ImgUpload::getImgUrlById($tmpMateriaRow['img_id']);
            }


            $tmpOrderMaterialRow['unit'] = $tmpMateriaRow['unit'];
            $tmpOrderMaterialRow['product_no'] = $tmpMateriaRow['product_no'];
            $orderMaterialList[] = $tmpOrderMaterialRow;
        }

        //处理图片数据
        $imgIdList = explode(',', $orderInfo['production_case_diagram']);
        $exampleImg = '';
        $imgNum = 0;
        foreach ($imgIdList as $imgId) {
            if (!trim($imgId)) {//过滤空格 图片id应该不会有0
                continue;
            }
            $imgNum++;
            if (!$exampleImg) {//取第一张图作为示例图
                $exampleImg = ImgUpload::getImgUrlById($imgId);
            }
        }


        //获取上一个部门&上一个部门
        $preProcessList = OrderType::getAllPrevOrderProcess($orderInfo['order_type'], $orderProcessInfo['process_type'])->toArray();
        //获取预估完成时间最晚的一个，待开工的部门优先级最高
        $preProcess = '';//上一个工序（部门）
        $preProcessEstimatedTime = 0;
        $preProcessEstimatedTimeStr = '';
        $lastOrderProcessId = 0;
        $finishNum = 0;
        $preProcessMeasurementUnit = '';
        $isPreEmpty = 0;
        if ($preProcessList) {
            foreach ($preProcessList as $processId) {
                //获取工序信息
                $tmpOrderProcessInfo = OrderProcess::where(['order_id' => $orderInfo['id'], 'process_type' => $processId])->first()->toArray();
                $lastOrderProcessId = $tmpOrderProcessInfo['id'];

                //获取工序数量是否需要叠加&工序名称
                $where = ['id' => $processId];
                $process = Process::getInfo($where)->toArray();
                $preProcess = $process['title'];//工序名称
                $processIsSum = $process['is_sum'];//工序数量是否累加 0-不累加 1-累加

                if ($tmpOrderProcessInfo['status'] == 1) {//待开工
                    $preProcessEstimatedTimeStr = '待开工';
                    break;
                } else {

                    //调整-预计完成时间调整为从员工工单获取
                    $orderProcessCourseList = OrderProcessCourse::where(['order_process_id' => $tmpOrderProcessInfo['id']])->get();
                    $finishNum = 0;

                    $finishUserNumList = [];
                    foreach ($orderProcessCourseList as $orderProcessCourseRow) {


                        $tmpPreProcessEstimatedTime = $orderProcessCourseRow['start_time'] + $orderProcessCourseRow['estimated_time_hour'] * 3600 + $orderProcessCourseRow['estimated_time_minute'] * 60;
                        if ($tmpPreProcessEstimatedTime > $preProcessEstimatedTime) {
                            $preProcessEstimatedTime = $tmpPreProcessEstimatedTime;
                            $preProcessEstimatedTimeStr = date('Y年m月d日H时', $preProcessEstimatedTime);
                        }

                        //设定的角色不进行统计数量到工序数量中
                        //过滤异常数据
                        if (!DepartmentUser::getCurrentInfo($orderProcessCourseRow['uid'])) {
                            continue;
                        }
                        $tmpUserInfo = DepartmentUser::getCurrentInfo($orderProcessCourseRow['uid'])->toArray();
                        $tmpPrivilegeId = $tmpUserInfo['privilege_id'];
                        if (OrderEngine::getProcessNumNoStatistics($tmpPrivilegeId)) {
                            continue;
                        }

                        $finishNum += $orderProcessCourseRow['finish_number'];
                        if (!$processIsSum) {//不累加
                            $tmpUserInfo = DepartmentUser::getCurrentInfo($orderProcessCourseRow['uid'])->toArray();
                            $tmpPrivilegeId = $tmpUserInfo['privilege_id'];
                            if (isset($finishUserNumList[$tmpPrivilegeId])) {
                                $finishUserNumList[$tmpPrivilegeId]['finish_number'] += $orderProcessCourseRow['finish_number'];
                            } else {
                                $finishUserNumList[$tmpPrivilegeId]['finish_number'] = $orderProcessCourseRow['finish_number'];
                            }
                        }
                    }


                    if ($preProcessEstimatedTime < 631152000) {//过滤1970的情况
                        $preProcessEstimatedTimeStr = '';
                    }

                    //不累加--未完工时取完成量最小的员工
                    if (!empty($finishUserNumList)) {
                        $finishMinNum = '';
                        foreach ($finishUserNumList as $finishUserNumRow) {
                            if ($finishMinNum === 0) {//如果有员工完成数量为0，
                                break;
                            }

                            if ($finishUserNumRow['finish_number'] < $finishMinNum || $finishMinNum === '') {//如果有员工完成数量更少，或者第一个员工的数据
                                $finishMinNum = $finishUserNumRow['finish_number'];
                            }
                        }
                        $finishNum = $finishMinNum;
                        $preProcessMeasurementUnit = $process['measurement_unit'];
                    }


                }
            }
        } else {
            $preProcess = '无';//上一个工序（部门）
            $preProcessEstimatedTimeStr = '';
            $isPreEmpty = 1;
        }


        //获取工序类型名称
        $orderTypeTitle = OrderType::getOneValueById($orderInfo['order_type'], 'title');
        
        //增加后台配置的工序废料
        $ordertypeProcessWasteList = [];
        $ordertypeProcessId = $orderProcessInfo['ordertype_process_id'];
        $ordertypeProcessWasteListObj = \App\Eloquent\Ygt\OrdertypeProcessWaste::where(['ordertype_process_id'=>$ordertypeProcessId])->get();

        if($ordertypeProcessWasteListObj){
            foreach ($ordertypeProcessWasteListObj as $ordertypeProcessWasteRow){
                $ordertypeProcessWasteList[] = [
                    'id' => $ordertypeProcessWasteRow['id'],
                    'title' => $ordertypeProcessWasteRow['title'],
                    'unit' => "kg",
                    'placeholder' => "请填写废品数量",
                ];
            }
        }


        $return = [];
        $return['product_name'] = $orderTypeTitle;//产品名称
        $return['order_title'] = $orderInfo['order_title'];//生产单号3
        $return['finished_date'] = $orderInfo['finished_date'];//交货日期
        $return['estimated_time'] = $preProcessEstimatedTimeStr;//预计完成
        $return['last_order_process_finish_num'] = $finishNum.$preProcessMeasurementUnit;//上一工序完成数量
        $return['img_url'] = $exampleImg;//示例图
        $return['img_title'] = '共' . $imgNum . '张图片';//示例图文字提示
        $return['last_department'] = $preProcess;//上一部门
        $return['last_order_process_id'] = $lastOrderProcessId;//上一工序
        $return['jump_tips'] = '已接单[' . $processTitle . ']';//跳转到工单详情文字提示
        $return['order_material_list'] = $orderMaterialList;//领取材料列表
        $return['img_order_id'] = $orderInfo['id'];//主工单id
        $return['order_process_course_id'] = $orderProcessCourseId;//用料提交ID
        $return['order_process_id'] = $orderProcessInfo['id'];//工艺工单ID
        $return['ordertype_process_waste_list'] = $ordertypeProcessWasteList;//工序废品列表
        $return['is_pre_empty'] = $isPreEmpty;//1-没有上一工序 0-有

        return $return;
    }

    //工序管理员用料情况提交
    public function orderProcessManageUseMaterialSubmit(Request $request)
    {
        //获取登陆用户信息
        $userId = \App\Engine\Func::getHeaderValueByName('userid');
        $userInfo = \App\Eloquent\Ygt\DepartmentUser::getCurrentInfo($userId)->toArray();

        //获取传入数据
        $input = $request->all();
        $input['order_process_course_id'] = isset($input['order_process_course_id']) ? $input['order_process_course_id'] : '';

        if ($input['material_list']) {
            $input['material_list'] = \GuzzleHttp\json_decode(htmlspecialchars_decode($input['material_list']), true);
        } else {
            $input['material_list'] = [];
        }


        //工序废品信息
        if ($input['process_waste_list']) {
            $processWasteList = \GuzzleHttp\json_decode(htmlspecialchars_decode($input['process_waste_list']), true);
        } else {
            $processWasteList = [];
        }


        //逻辑调整传入的id实际为员工工单id
        $orderProcessCourseId = $input['order_process_course_id'];
        $orderProcessCourseRow = OrderProcessCourse::where(['id' => $orderProcessCourseId])->first()->toArray();


        //校验参数
        $rules = [
            'order_process_course_id' => 'required',
        ];
        $messages = [
            'order_process_course_id.required' => '缺少工单id',
        ];
        $this->validateRequestParameters($input, $rules, true, $messages);

        //获取对应工单工序表信息
        $orderProcessInfo = OrderProcess::where('id', $orderProcessCourseRow['order_process_id'])->first()->toArray();
        $curOrderProcessId = $orderProcessInfo['id'];
        //获取工单信息
        $orderInfo = Order::where('id', $orderProcessInfo['order_id'])->first()->toArray();
        $order_title = $orderInfo['order_title'];
        $foreignKey = intval($orderInfo['customer_order_id']);
        //获取工序名称
        $processTitle = Process::getOneValueById($orderProcessInfo['process_type'], 'title');
        //校验数据
        if (!empty($input['material_list'])) {
            foreach ($input['material_list'] as $materialRow) {
                $orderMaterialObj = OrderMaterialCourse::where(['order_process_course_id' => $orderProcessCourseId, 'process_type' => $orderProcessInfo['process_type'], 'material_id' => $materialRow['material_id']])->first();
//                if($orderMaterialObj->status == 2){
//                    return [
//                        'code' => 1,
//                        'message' => '请勿重复提交'
//                    ];
//                }

                //如果是集合材料，将ID转为sku材料的ID（取集合材料关联第一个sku材料）
                $materialId = $materialRow['material_id'];
                if(strstr($materialId,'A')){
                    $tmpAssemblageMaterialId = str_replace('A','',$materialId);
                    $tmpMaterialRow = \App\Eloquent\Ygt\Product::where(['assemblage_material_id'=>$tmpAssemblageMaterialId])->first();
                    if($tmpMaterialRow){
                        $materialRow['material_id'] = $tmpMaterialRow->id;
                    }
                }else{
                    //通过扫码领取记录，调整二维码记录
                    //取最新的一条余品回退数据（如果有的话）
                    $orderMaterialQrLogRow = \App\Eloquent\Ygt\OrderMaterialQrLog::where(['type'=>1,'material_id'=>$materialId,'order_process_course_id'=>$input['order_process_course_id']])->orderBy('id','desc')->first();
                    if($orderMaterialQrLogRow){
                        //修改码的数据
                        $tmpQrcodeRow = \App\Eloquent\Ygt\Qrcode::where(['id'=>$orderMaterialQrLogRow['qr_id']])->first();
                        if($tmpQrcodeRow){
                            if($tmpQrcodeRow->is_inuse == 1){
                                $tmpQrcodeRow->now_number = 0;//兼容老的数据
                            }
                            $tmpQrcodeRow->now_number += $orderMaterialQrLogRow['num'];
                            $tmpQrcodeRow->is_inuse = 0;
                            $tmpQrcodeRow->save();
                        }
                    }

//                    $tmpInsertRow = [
//                        'order_process_course_id' => $orderProcessId,
//                        'material_id' => $materialId,
//                        'qr_id' => $qrId,
//                        'type' => $type,
//                        'num' => $num,
//                    ];
//                    $orderMaterialQrLogObj->fill($tmpInsertRow);
//                    $orderMaterialQrLogObj->save();


                }
//                if (!$materialRow['residual_number'] && $materialRow['residual_number'] !== '0') {
//                    return [
//                        'code' => 1,
//                        'message' => '请填写余品数量'
//                    ];
//                }

                if($materialRow['residual_number']){//防止出现 0 > null
                    $curResidualNumber = $materialRow['residual_number'] + $orderMaterialObj['residual_number'];
                    if ($curResidualNumber > $orderMaterialObj->receive_number ) {
                        return [
                            'code' => 1,
                            'message' => '余品数量不能超过领取材料总数'
                        ];
                    }
                }


//                if (!$materialRow['scrap_number'] && $materialRow['scrap_number'] !== '0') {
//                    return [
//                        'code' => 1,
//                        'message' => '请填写废品数量'
//                    ];
//                }

                if($materialRow['scrap_number']) {//防止出现 0 > null
                    $curScrapNumber = $materialRow['scrap_number'] + $orderMaterialObj['scrap_number'];
                    if ($curScrapNumber > $orderMaterialObj->receive_number) {
                        return [
                            'code' => 1,
                            'message' => '废品数量不能超过领取材料总数'
                        ];
                    }
                }


//                if (!$materialRow['retreat_number'] && $materialRow['retreat_number'] !== '0') {
//                    return [
//                        'code' => 1,
//                        'message' => '请填写退品数量'
//                    ];
//                }

                if($materialRow['retreat_number']) {//防止出现 0 > null
                    $curRetreatNumber = $materialRow['retreat_number'] + $orderMaterialObj['retreat_number'];
                    if ($curRetreatNumber > $orderMaterialObj->receive_number) {
                        return [
                            'code' => 1,
                            'message' => '退品数量不能超过领取材料总数'
                        ];
                    }
                }
            }
        }



        //分批提交记录-批次记录
        $tmpObj = \App\Eloquent\Ygt\OrderProcessMaterialSubmit::firstOrNew(['id'=>'']);
        $tmpInsertRow = [
            'order_id' => $orderInfo['id'],
            'order_process_id' => $orderProcessInfo['id'],
            'order_process_course_id' => $orderProcessCourseId,
            'uid' => $userId,
            'company_id' => $orderInfo['company_id'],
        ];
        $tmpObj->fill($tmpInsertRow);
        $tmpObj->save();
        $orderProcessMaterialSubmitId = $tmpObj->id;


        $retreatMaterialList = [];//记录退品信息
        //工单材料表添加剩余数量、废品数量
        $materialWasteList = [];
        $materialResidueList = [];
        if (!empty($input['material_list'])) {
            foreach ($input['material_list'] as $materialRow) {
                $orderMaterialObj = OrderMaterialCourse::where(['order_process_course_id' => $orderProcessCourseId, 'process_type' => $orderProcessInfo['process_type'], 'material_id' => $materialRow['material_id']])->first();

                //如果是集合材料，将ID转为sku材料的ID（取集合材料关联第一个sku材料）
                $materialId = $materialRow['material_id'];
                if(strstr($materialId,'A')){
                    $tmpAssemblageMaterialId = str_replace('A','',$materialId);
                    $tmpMaterialRow = \App\Eloquent\Ygt\Product::where(['assemblage_material_id'=>$tmpAssemblageMaterialId])->first();
                    if($tmpMaterialRow){
                        $materialRow['material_id'] = $tmpMaterialRow->id;
                    }
                }

                //分批提交记录-详情
                $tmpObj = \App\Eloquent\Ygt\OrderProcessMaterialSubmitDetail::firstOrNew(['id'=>'']);
                $tmpInsertRow = [
                    'order_process_material_submit_id' => $orderProcessMaterialSubmitId,
                    'order_id' => $orderInfo['id'],
                    'order_process_id' => $orderProcessInfo['id'],
                    'order_process_course_id' => $orderProcessCourseId,
                    'type' => 1,
                    'relate_id' => $materialRow['material_id'],
                    'residual_number' => $materialRow['residual_number'],
                    'scrap_number' => $materialRow['scrap_number'],
                    'retreat_number' => $materialRow['retreat_number'],
                    'place_name' => isset($materialRow['place_name']) ? $materialRow['place_name'] : '',
                    'company_id' => $orderInfo['company_id'],
                ];
                $tmpObj->fill($tmpInsertRow);
                $tmpObj->save();


                //材料废品记录
                if($materialRow['scrap_number']){
                    $materialWasteList[]=[
                        'id' => $materialRow['material_id'],
                        'num' => $materialRow['scrap_number'],
                    ];
                }

                //材料余品记录
                if($materialRow['residual_number']){
                    $materialResidueList[]=[
                        'id' => $materialRow['material_id'],
                        'num' => $materialRow['residual_number'],
                    ];
                }

                //如果有退品数量，记录数据，统一处理
                if ($materialRow['retreat_number']) {
                    $retreatMaterialList[] = $materialRow;
                }



                //增加废品总价
                $materialDetailInfo = ProductEngine::getProductInfo($materialRow['material_id']);//材料详细信息

                $orderMaterialObj->residual_number += $materialRow['residual_number'];
                $orderMaterialObj->scrap_number += $materialRow['scrap_number'];
                $orderMaterialObj->retreat_number += $materialRow['retreat_number'];
                $orderMaterialObj->residual_place_name = isset($materialRow['place_name']) ? $materialRow['place_name'] : '';
                $orderMaterialObj->scrap_price = $materialDetailInfo['price'] * $orderMaterialObj['scrap_number'];
                $orderMaterialObj->save();

            }
        }



        $companyId = $orderProcessInfo['company_id'];


        //材料有余品，发送消息给仓库
        $tmpOrderTitle = \App\Engine\Common::changeSnCode($orderInfo['order_title']);
        $productName = \App\Engine\OrderEngine::getOrderFiledValueTrue($orderInfo['product_name'], 20);
        $messageContent = "工单号:{$tmpOrderTitle}rnrn";
        $messageContent.= "品名:{$productName}rnrn";
        if (!empty($materialResidueList)) {
//            $messageContent = "工单中有退品rnrn";
            $messageContent .= "以下材料有余品：rnrn";

            foreach ($materialResidueList as $materialResidueRow) {
                $tmpMaterialId = $materialResidueRow['id'];
                $tmpMaterialResidueNum = $materialResidueRow['num'];

                $tmpMaterialRow = \App\Engine\Product::getProductInfo($tmpMaterialId);
                $tmpMaterialName = $tmpMaterialRow['product_name'];
                $tmpMaterialUnit = $tmpMaterialRow['unit'];

                $messageContent .= "{$tmpMaterialName} 余 {$tmpMaterialResidueNum}（{$tmpMaterialUnit}）rnrn";
            }


            //发送消息给仓库
            $purchasingAgentPrivilegeList = \App\Eloquent\Ygt\Privilege::getPrivilegeIds($companyId, 7);

            foreach ($purchasingAgentPrivilegeList as $purchasingAgentPrivilegeId) {
                if($purchasingAgentPrivilegeId){
                    $data = [
                        'company_id' => $companyId,
                        'privilege_id' => $purchasingAgentPrivilegeId,
                        'form_user_id' => $orderProcessCourseRow['uid'],
                        'to_user_id' => '',
                        'foreign_key' => $foreignKey,
                        'type' => 35,//临时跳转，不跳详情
                        'type_id' => $orderProcessInfo['id'],
                        'title' => $orderInfo['order_title'],
                        'content' => $messageContent,
                        'type_status' => 1,
                        'theme' => '材料有余品产生',
                    ];
                    UserMessage::sendCustomerOrderMessage($data);
                }
            }
        }


        //退品材料发送消息给采购员
        /*"来源：领料员
主题：材料有退品产生
内容：工单号、品名、退品名称、数量、原因"
*/
        $tmpOrderTitle = \App\Engine\Common::changeSnCode($orderInfo['order_title']);
        $productName = \App\Engine\OrderEngine::getOrderFiledValueTrue($orderInfo['product_name'], 20);
        $messageContent = "工单号:{$tmpOrderTitle}rnrn";
        $messageContent.= "品名:{$productName}rnrn";

        if (!empty($retreatMaterialList)) {
//            $messageContent = "工单中有退品rnrn";
            $messageContent .= "以下材料有退品：rnrn";

            foreach ($retreatMaterialList as $retreatMaterialRow) {
                $tmpMaterialId = $retreatMaterialRow['material_id'];
                $tmpMaterialRetreatNum = $retreatMaterialRow['retreat_number'];

                $tmpMaterialRow = \App\Engine\Product::getProductInfo($tmpMaterialId);
                $tmpMaterialName = $tmpMaterialRow['product_name'];
                $tmpMaterialUnit = $tmpMaterialRow['unit'];

                $messageContent .= "{$tmpMaterialName} 退 {$tmpMaterialRetreatNum}（{$tmpMaterialUnit}）rnrn";

                //退品保存到材料退品表
                //获取集合材料ID
                $tmpAssemblageMaterialId = '';
                if($tmpMaterialRow){
                    $tmpAssemblageMaterialId = $tmpMaterialRow['assemblage_material_id'];
                }

                $tmpMaterialRetreatObj = \App\Eloquent\Ygt\MaterialRetreat::firstOrNew(['material_id'=>$tmpMaterialId,'company_id'=>$companyId]);
                if($tmpMaterialRetreatObj->id){
                    //如果存在
                    $tmpInsertRow = [
                        'number_all' => $tmpMaterialRetreatObj['number_all']+$tmpMaterialRetreatNum,
                        'number' => $tmpMaterialRetreatObj['number']+$tmpMaterialRetreatNum,
                    ];
                    $tmpMaterialRetreatObj->fill($tmpInsertRow);
                    $tmpMaterialRetreatObj->save();
                }else{
                    $tmpInsertRow = [
                        'material_id' => $retreatMaterialRow['material_id'],
                        'assemblage_material_id' => $tmpAssemblageMaterialId,
                        'number_all' => $tmpMaterialRetreatNum,
                        'number' => $tmpMaterialRetreatNum,
                        'company_id' => $companyId,
                    ];
                    $tmpMaterialRetreatObj->fill($tmpInsertRow);
                    $tmpMaterialRetreatObj->save();
                }

                //添加流水
                $tmpMaterialRetreatId = $tmpMaterialRetreatObj->id;
                $tmpMaterialRetreatLogObj = \App\Eloquent\Ygt\MaterialRetreatLog::firstOrNew(['id'=>'']);


                ////生成流水号
                //获取是当天的第几条
                $dayStartTime = strtotime(date('Ymd'));
                $intradayOrderCount = \App\Eloquent\Ygt\MaterialRetreatLog::withTrashed()->where([['created_at', '>=', $dayStartTime]])->get()->count();
                $tmpIndex = '';
                $intradayOrderCount++;
                if ($intradayOrderCount < 10) {
                    $tmpIndex = sprintf('0%d', $intradayOrderCount);
                } else {
                    $tmpIndex = $intradayOrderCount;
                }
                $sn = 'CLTPLS' . date('ymd') . $tmpIndex;


                $tmpInsertRow = [
                    'material_retreat_id' => $tmpMaterialRetreatId,
                    'material_id' => $retreatMaterialRow['material_id'],
                    'number' => $tmpMaterialRetreatNum,
                    'user_id' => $userId,
                    'sn' => $sn,
                    'type' => 1,
                    'relate_id' => $orderProcessMaterialSubmitId,
                ];
                $tmpMaterialRetreatLogObj->fill($tmpInsertRow);
                $tmpMaterialRetreatLogObj->save();
            }


            //发送消息给采购员
            $purchasingAgentPrivilegeList = \App\Eloquent\Ygt\Privilege::getPrivilegeIds($companyId, 10);

            foreach ($purchasingAgentPrivilegeList as $purchasingAgentPrivilegeId) {
                $data = [
                    'company_id' => $companyId,
                    'privilege_id' => $purchasingAgentPrivilegeId,
                    'form_user_id' => $orderProcessCourseRow['uid'],
                    'to_user_id' => '',
                    'foreign_key' => $foreignKey,
                    'type' => 35,//临时跳转，不跳详情
                    'type_id' => $orderProcessMaterialSubmitId,
                    'title' => $orderInfo['order_title'],
                    'content' => $messageContent,
                    'type_status' => 1,
                    'theme' => '材料有退品产生',
                ];
                UserMessage::sendCustomerOrderMessage($data);
            }
        }


        //修改工单材料状态
        $tmpOrderMaterialObjList = OrderMaterialCourse::where(['order_process_course_id' => $orderProcessCourseId, 'process_type' => $orderProcessInfo['process_type']])->get();
        foreach ($tmpOrderMaterialObjList as $tmpOrderMaterialObj){
            $tmpOrderMaterialObj->status = 2;
            $tmpOrderMaterialObj->save();
        }


        //剩余材料仓库入库
//        Stock::OrderProcessStockIn($orderProcessCourseId);
        if (!empty($input['material_list'])) {//如果没有取材料不走出入库方法
            Stock::OrderMaterialSubmitGradationStockIn($orderProcessMaterialSubmitId);
        }



        ////记录工单废品记录 zhuyujun 20180906
        //材料
        /*"来源：领料员
主题：材料有废品产生
内容：工单号、品名、废品名称、数量、原因"
*/
        $tmpOrderTitle = \App\Engine\Common::changeSnCode($orderInfo['order_title']);
        $productName = \App\Engine\OrderEngine::getOrderFiledValueTrue($orderInfo['product_name'], 20);
        $messageContent = "工单号:{$tmpOrderTitle}rnrn";
        $messageContent.= "品名:{$productName}rnrn";

        foreach ($materialWasteList as $materialWasteRow){
            $relateType = 1; //材料废品
            $relateId = $materialWasteRow['id'];
            $orderProcessWasteObj = \App\Eloquent\Ygt\OrderProcessWaste::firstOrNew(['id'=>'']);
            $tmpInsertRow = [
                'order_id' => $orderInfo['id'],
                'order_process_id'=> $orderProcessInfo['id'],
                'order_process_material_submit_id'=> $orderProcessMaterialSubmitId,
                'relate_type'=> $relateType,
                'relate_id'=> $relateId,
                'number'=> $materialWasteRow['num'],
            ];
            $orderProcessWasteObj->fill($tmpInsertRow);
            $orderProcessWasteObj->save();

            $tmpMaterialRow = \App\Engine\Product::getProductInfo($relateId);
            $tmpMaterialName = $tmpMaterialRow['product_name'];
            $tmpMaterialUnit = $tmpMaterialRow['unit'];

            $messageContent .= "{$tmpMaterialName} 废 {$materialWasteRow['num']}（{$tmpMaterialUnit}）rnrn";

        }

        //工序废品
        foreach ($processWasteList as $processWasteRow){
            if(isset($processWasteRow['num']) && $processWasteRow['num']){
                $relateType = 2; //工序废品
                $relateId = $processWasteRow['id'];

                //分批提交记录-详情
                $tmpObj = \App\Eloquent\Ygt\OrderProcessMaterialSubmitDetail::firstOrNew(['id'=>'']);
                $tmpInsertRow = [
                    'order_process_material_submit_id' => $orderProcessMaterialSubmitId,
                    'order_id' => $orderInfo['id'],
                    'order_process_id' => $orderProcessInfo['id'],
                    'order_process_course_id' => $orderProcessCourseId,
                    'type' => 2,
                    'relate_id' => $relateId,
                    'residual_number' => 0,
                    'scrap_number' => $processWasteRow['num'],
                    'retreat_number' => 0,
                    'place_name' => isset($processWasteRow['place_name']) ? $processWasteRow['place_name'] : '',
                    'company_id' => $orderInfo['company_id'],
                ];
                $tmpObj->fill($tmpInsertRow);
                $tmpObj->save();


                $orderProcessWasteObj = \App\Eloquent\Ygt\OrderProcessWaste::firstOrNew(['id'=>'']);
                $tmpInsertRow = [
                    'order_id' => $orderInfo['id'],
                    'order_process_id'=> $orderProcessInfo['id'],
                    'order_process_material_submit_id'=> $orderProcessMaterialSubmitId,
                    'relate_type'=> $relateType,
                    'relate_id'=> $relateId,
                    'number'=> $processWasteRow['num'],
                ];
                $orderProcessWasteObj->fill($tmpInsertRow);
                $orderProcessWasteObj->save();


                $tmpProcessWasteName = '';
                $tmpOrdertypeProcessWasteRow = \App\Eloquent\Ygt\OrdertypeProcessWaste::where(['id'=>$relateId])->first();
                if($tmpOrdertypeProcessWasteRow){
                    $tmpProcessWasteName = $tmpOrdertypeProcessWasteRow['title'];
                }

                $messageContent .= "{$tmpProcessWasteName} 废 {$processWasteRow['num']}（千克）rnrn";
            }
        }

        ////如有废料，发送消息给废品员
        if(!empty($materialWasteList) || !empty($processWasteList)){
            $companyId = $orderProcessInfo['company_id'];
            //废品员权限
            $privilegeIdList = \App\Engine\OrderEngine::getPrivilegeByNode($companyId, 15);
            $userId = \App\Engine\Func::getHeaderValueByName('userid');
            foreach ($privilegeIdList as $privilegeId) {
                if ($privilegeId) {
                    $messageData = [
                        'company_id' => $companyId,
                        'privilege_id' => $privilegeId,
                        'form_user_id' => $userId,
                        'to_user_id' => '',
                        'foreign_key' => $foreignKey,
                        'type' => 39,
                        'type_id' => $orderProcessMaterialSubmitId,
                        'title' => '有新的工单废料',
                        'content' => $messageContent,
                        'type_status' => 1,
                        'theme' => '材料有废品产生',
                    ];
                    UserMessage::sendCustomerOrderMessage($messageData);
                }
            }
        }

        return '提交成功';
    }


    //入库筛选页面
    public function getPurchaseFilterDetail()
    {
        //获取采购申请的详情
        $workFlowId = request('workflow_id');
        $rey = new \App\Repositories\OA\WorkflowRepository();
        $workflow = $rey->find(['id' => $workFlowId], ['workflowLogList.fileList']);
        $purchaseId = $workflow['related_id'];
        $purchaseRow = \App\Eloquent\Ygt\Purchase::where(['id' => $purchaseId])->first()->toArray();
        $purchaseMaterialList = \App\Eloquent\Ygt\PurchaseMaterial::where(['purchase_id' => $purchaseId])->get()->toArray();
        $materialList = [];
        $allSumMoney = '';//所有材料总价
        foreach ($purchaseMaterialList as $purchaseMaterialRow) {
            //获取材料名称
            $materialRow = \App\Engine\Product::getProductInfo($purchaseMaterialRow['material_id']);

            //追加材料图片地址
            $materialRow['img_url'] = '';
            if ($materialRow['img_id']) {
                $materialRow['img_url'] = \App\Eloquent\Ygt\ImgUpload::getImgUrlById($materialRow['img_id']);
            }

            //追加材料自定义属性
            $ProductFieldsModel = new \App\Eloquent\Ygt\ProductFields();
            $where = ['assemblage_material_id' => $materialRow['assemblage_material_id']];
            $productFields = \App\Eloquent\Ygt\ProductFields::where($where)->get();

            $productFields = $productFields->map(function ($item) {
                $data['field_name'] = $item->field_name;
                $data['is_compute'] = $item->is_compute;
                $comumnName = \App\Engine\Product::getFieldColumn($item->field_type);
                $data['field_value'] = $item->$comumnName;
                $data['unit'] = $item->unit;
                return $data;
            });

            //过滤计量属性
            $productFields = $productFields->toArray();
            foreach ($productFields as $key => $row){
                if($row['is_compute']){
                    unset($productFields[$key]);
                }
            }
            $productFields = array_values($productFields);

            $materialRow['custom_fields'] = $productFields;

            $firstText = $secondText = $thirdText = $fourthText = '';
            $fieldsArr = $productFields;
            if (!empty($fieldsArr)) {
                if (isset($fieldsArr[0])) {
                    $firstText = $fieldsArr[0]['field_name'] . ': ' . $fieldsArr[0]['field_value']. $fieldsArr[0]['unit'];
                }
                if (isset($fieldsArr[1])) {
                    $secondText = $fieldsArr[1]['field_name'] . ': ' . $fieldsArr[1]['field_value']. $fieldsArr[1]['unit'];
                }
                if (isset($fieldsArr[2])) {
                    $thirdText = $fieldsArr[2]['field_name'] . ': ' . $fieldsArr[2]['field_value']. $fieldsArr[2]['unit'];
                }
                if (isset($fieldsArr[3])) {
                    $fourthText = $fieldsArr[3]['field_name'] . ': ' . $fieldsArr[3]['field_value']. $fieldsArr[3]['unit'];
                }
            }

            //处理字段
//            $lists[$key]['first_text']   = $firstText;
//            $lists[$key]['second_text']  = $secondText;
//            $lists[$key]['third_text']   = $thirdText;


            $showMaterialRow = [
                'material_id' => $materialRow['id'],
                'product_name' => $materialRow['product_name'],
                'img_url' => $materialRow['img_url'],
                'custom_fields' => $materialRow['custom_fields'],
                'price' => $purchaseMaterialRow['price'],
                'num' => $purchaseMaterialRow['num'],
                'sum_money' => $purchaseMaterialRow['price'] * $purchaseMaterialRow['num'],//总价
                'first_text' => $firstText,//材料属性
                'second_text' => $secondText,//材料属性
                'third_text' => $thirdText,//材料属性
                'fourth_text' => $fourthText,//材料属性
                'unit' => $materialRow['unit'],
            ];

            $allSumMoney += $showMaterialRow['sum_money'];

            $materialList[] = $showMaterialRow;
        }

        //交货日期
        $finishDate = '';
        if ($purchaseRow['finished_date']) {
            $finishDate = date('Y.m.d', strtotime($purchaseRow['finished_date']));
        }

        //获取供应商信息
        $supplierRow = \App\Eloquent\Ygt\SellerCompany::where(['id' => $purchaseRow['supplier_id']])->first();

        $supplierName = $supplierTel = '';
        if ($supplierRow) {
            $supplierName = $supplierRow['title'];
            $supplierTel = $supplierRow['contact_mobile'];
        }
        
        //收货地址，取采购员所在企业的收货地址
        $purchaseUid = $purchaseRow['uid'];
        $purchaseUserInfo = \App\Eloquent\Ygt\DepartmentUser::getCurrentInfo($purchaseUid)->toArray();

        $address = '';
        $companyRow = \App\Eloquent\Ygt\Company::where(['id'=>$purchaseUserInfo['company_id']])->first();
        if($companyRow){
            $companyProvinceName = $companyRow['province_name'] ? $companyRow['province_name'] : '';
            $companyCityName = $companyRow['city_name'] ? $companyRow['city_name'] : '';
            $companyAreaName = $companyRow['area_name'] ? $companyRow['area_name'] : '';
            $companyAddress = $companyRow['address'] ? $companyRow['address'] : '';

            $address = $companyProvinceName.$companyCityName.$companyAreaName.$companyAddress;
        }

        $content = [
            'material_list' => $materialList,//采购材料名称（所有）
            'page_title' => $supplierName . '发货单',//页面头部文字提示
            'name' => $supplierName,//供应商名称
            'tel' => $supplierTel,//供应商号码
            'date' => $finishDate,//交货日期
            'address' => '收货地址：'.$address,//发货地址
        ];
        return $content;
    }

    //入库筛选页面提交
    public function getPurchaseFilterSubmit()
    {
        $userId = Func::getHeaderValueByName('userid');
        $userInfo = DepartmentUser::getCurrentInfo($userId)->toArray();
        $companyId = $userInfo['company_id'];

        $workFlowId = request('workflow_id');
//        $materialIdArr = request('material_id_arr');
        $submitMaterialList = request('material_list');


        $workFlowId = request('workflow_id');
        $rey = new \App\Repositories\OA\WorkflowRepository();
        $workflow = $rey->find(['id' => $workFlowId], ['workflowLogList.fileList']);


        //如果流程已结束，拒绝重复提价
        if ($workflow['dispose_code'] == '1100' && 0) {
            return [
                'code' => 1,
                'message' => '数据已提交，请刷新页面'
            ];
        }

        $purchaseId = $workflow['related_id'];
        $purchaseRow = \App\Eloquent\Ygt\Purchase::where(['id' => $purchaseId])->first()->toArray();


        $allMoney = 0;
        $msgCl = 'rnrn入库详情：rnrn[材料][数量][单价]';
        $materialIdList = [];
        $autoAddMaterialList = [];
        $receiveMaterialPriceAll = 0;
        if ($submitMaterialList) {
            $submitMaterialList = \GuzzleHttp\json_decode(htmlspecialchars_decode($submitMaterialList), true);
            foreach ($submitMaterialList as $submitMaterialRow) {
                $materialId = $submitMaterialRow['material_id'];
                $submitMaterialNum = $submitMaterialRow['number'];
                $submitMaterialPlaceName = isset($submitMaterialRow['place_name']) ? $submitMaterialRow['place_name'] : '';

                $purchaseMaterialObj = \App\Eloquent\Ygt\PurchaseMaterial::where(['purchase_id' => $purchaseId, 'material_id' => $materialId])->first();
                if ($purchaseMaterialObj) {
                    $purchaseMaterialObj->is_accept = 1;
                    $purchaseMaterialObj->save();

                    $autoAddMaterialList[] = [
                        'product_id' => $materialId,//材料id
                        'number' => $submitMaterialNum,//材料数量
                        'unit_price' => $purchaseMaterialObj->price ? $purchaseMaterialObj->price : 0,//单价
                        'distribution_company' => '',//单位
                        'distribution_time' => 0,//配送时间--时间戳
                        'contact_number' => '',//联系方式
                        'remark' => '',//备注
                        'place_name' => $submitMaterialPlaceName,//堆位
                        'is_print' => 0,//是否打印--固定0
                        'non_arr' => '',
                    ];

                    $receiveMaterialUnitPrice = $purchaseMaterialObj->price ? $purchaseMaterialObj->price : 0;//单价
                    $receiveMaterialNumber = $purchaseMaterialObj->num;//材料数量

                    $receiveMaterialPriceAll += $receiveMaterialUnitPrice * $receiveMaterialNumber;
                    //采购入库的时候，自动修改对应材料的单价
                    $tmpObj = \App\Eloquent\Ygt\Product::where(['id'=>$materialId])->first();
                    $tmpObj->price = $purchaseMaterialObj->price ? $purchaseMaterialObj->price : 0;
                    $tmpObj->save();

                    $msgCl .= "rnrn[$tmpObj->product_name][$submitMaterialNum][$receiveMaterialUnitPrice]";

                    $allMoney+=$submitMaterialNum*$receiveMaterialUnitPrice;
                }
            }
        } else {
            return [
                'code' => 1,
                'message' => '未选择材料'
            ];
        }

        //完成审核
        $token = \App\Engine\Func::getHeaderValueByName('tokenall');
        $imei = \App\Engine\Func::getHeaderValueByName('imei');
        $header = [
            'TOKEN: ' . $token,
            'IMEI: ' . $imei
        ];
        $url = env('APP_URL');
        $url .= '/api/oa/workflow/handle';

        $param = 'operation_type=agree&is_stop_flow=1&workflow_id=' . $workFlowId;
        $curl = curl_init();

        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_HEADER, 1);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $param);
        $curl_result = curl_exec($curl);
        curl_close($curl);


        ////自动添加材料流水
        //需添加的材料
        \App\Eloquent\Ygt\StockIn::waterAddPostCurl($autoAddMaterialList, $header);


        ////增加采购应付单
        $data = [
            'company_id' => $purchaseRow['company_id'],//厂id
            'seller_company_id' => $purchaseRow['supplier_id'],//厂的供应商id
            'money' => $receiveMaterialPriceAll,//金额
            'pay_type' => $purchaseRow['payment_method'],//付款方式
            'add_user_id' => $purchaseRow['uid'],//添加人UID，调整为发起人的ID，否则对应的供应商账单将不显示
        ];
        $result = \App\Eloquent\Ygt\SellerBill::insertOneDataByType($data);

        //组织消息信息
        $order_id = $purchaseRow['order_id'];
        $order_title = '';
        $xd_uid = 0;
        $customer_id = 0;
        if($order_id){
            $order_info = \App\Eloquent\Ygt\Order::where('id','=',$order_id)->first();
            if($order_info){
                $order_info = $order_info->toArray();
                $order_title = $order_info['order_title'];
                $xd_uid = $order_info['uid'];
                $customer_id = $order_info['customer_name'];
            }
        }

        //获得供应商信息
        $supplier_name = '';
        $supplier_mobile = '';
        $seller_company = \App\Eloquent\Ygt\SellerCompany::where('id','=',$purchaseRow['supplier_id'])->first();
        if($seller_company){
            $seller_company = $seller_company->toArray();
            $supplier_name = $seller_company['title'];
            $supplier_mobile = $seller_company['contact_mobile'];
        }
        //获得采购总金额
        $money = \App\Eloquent\Ygt\PurchaseMaterial::where('purchase_id','=',$purchaseId)->sum(DB::raw('num*price'));
        //发送消息给指定的人
        $foreignKey = $workFlowId;
        $messageContent = '工单号：'.$order_title;
        $messageContent .= 'rnrn供应商：'.$supplier_name;
        $messageContent .= 'rnrn供应商联系电话：'.$supplier_mobile;
        $messageContent .= 'rnrn采购单号：'.$purchaseRow['purchase_number'];
        $messageContent .= 'rnrn采购总金额：'.$money;
        $messageContent .= 'rnrn实际入库总金额：'.$allMoney;
        $messageContent .= $msgCl;
        //给采购员发消息
        $toUserId = $purchaseRow['uid'];//(英文逗号隔开)
        $type = 24;
        $typeId = $purchaseId;

        $messageData = [
            'company_id' => $companyId,
            'privilege_id' => 0,
            'form_user_id' => $userId,
            'to_user_id' => $toUserId,
            'foreign_key' => $foreignKey,
            'type' => $type,
            'type_id' => $typeId,
            'title' => '采购入库了',
            'content' => $messageContent,
            'type_status' => 1,
            'theme'=>"材料入库"
        ];
        UserMessage::sendWorkFlowMessage($messageData);

        //给下单人发消息
        if($xd_uid){
            $messageContent = '供应商：'.$supplier_name;
            $messageContent .= $msgCl;

            //获得客户名
            $customer_name = \App\Eloquent\Ygt\Customer::getOneValueById($customer_id,'customer_name');

            $messageData = [
                'company_id' => $companyId,
                'privilege_id' => 0,
                'form_user_id' => $userId,
                'to_user_id' => $xd_uid,
                'foreign_key' => $foreignKey,
                'type' => 35,
                'type_id' => $typeId,
                'title' => '采购入库了',
                'content' => $messageContent,
                'type_status' => 1,
                'theme'=>$customer_name."材料入库"
            ];
            UserMessage::sendWorkFlowMessage($messageData);
        }

//        //给财务发消息
//        $privilegeIdList = \App\Engine\OrderEngine::getPrivilegeByNode($companyId, 11);
//        foreach ($privilegeIdList as $privilegeId) {
//            if ($privilegeId) {
//                $messageData = [
//                    'company_id' => $companyId,
//                    'privilege_id' => $privilegeId,
//                    'form_user_id' => $userId,
//                    'to_user_id' => '',
//                    'foreign_key' => $foreignKey,
//                    'type' => 25,
//                    'type_id' => $typeId,
//                    'title' => '采购入库了',
//                    'content' => $messageContent,
//                    'type_status' => 1,
//                ];
//                UserMessage::sendWorkFlowMessage($messageData);
//            }
//        }

        return '提交成功';
    }


    //下单人查看工序管理员领取材料详情
    public function getOrderProcessManageReceiveMaterialDetail()
    {
        $orderProcessId = request('order_process_id');

        $orderProcessRow = \App\Eloquent\Ygt\OrderProcess::where(['id' => $orderProcessId])->first();
        $orderRow = \App\Eloquent\Ygt\Order::where(['id' => $orderProcessRow['order_id']])->first();

        //获取工序管理员领取的材料
        $materiaCourselList = [];//保存材料ID和领取数量的关系
        $orderMaterialCourseList = \App\Eloquent\Ygt\OrderMaterialCourse::where(['order_process_id' => $orderProcessId])->get();
        foreach ($orderMaterialCourseList as $orderMaterialCourseRow) {
            $materiaCourselList[$orderMaterialCourseRow['material_id']] = $orderMaterialCourseRow['receive_number'];
        }


        //获取材料详情
        $materialIdList = array_keys($materiaCourselList);
        $materialList = \App\Eloquent\Ygt\Product::whereIn('id', $materialIdList)->get();


        //添加图片地址
        $materialList = $materialList->map(function ($item) {
            $imgId = $item['img_id'];
            if ($imgId) {
                $exampleImg = ImgUpload::getImgUrlById($imgId, false);
                $item['img_url'] = $exampleImg;
            }
            return $item;
        });

        $materialList = \App\Engine\Product::composeList($materialList);


        $materialList = $materialList->map(function ($item) use ($materiaCourselList) {
            $item['receive_number'] = '';
            if (isset($materiaCourselList[$item['id']])) {
                $item['receive_number'] = $materiaCourselList[$item['id']];
            }

            //百分比始终100%
            $item['ratio'] = 1;
            return $item;
        });


        //处理图片数据
        $imgIdList = explode(',', $orderRow['production_case_diagram']);
        $exampleImg = '';
        $imgNum = 0;
        foreach ($imgIdList as $imgId) {
            if (!trim($imgId)) {//过滤空格 图片id应该不会有0
                continue;
            }
            $imgNum++;
            if (!$exampleImg) {//取第一张图作为示例图
                $exampleImg = ImgUpload::getImgUrlById($imgId);
            }
        }

        //获取工序类型名称
        $orderTypeTitle = \App\Engine\OrderType::getOneValueById($orderRow['order_type'], 'title');


        $re = [
            'productImage' => $exampleImg,//示例图地址
            'orderTypeTitle' => $orderTypeTitle,//工序类型名称
            'productOrderValue' => '生产单号:' . $orderRow['order_title'],//工单号
            'orderId' => $orderRow['id'],//工单ID，跳转时使用
            'finishDate' => $orderRow['finished_date'],//交货时间
            'imgTitle' => '共' . $imgNum . '张图片',//示例图文字提示
            'materialList' => $materialList,

        ];//接口返回的值

        return $re;


    }


    //订单价格确定记录
    public function getCustomerOrderPriceLog()
    {
        $customerOrderId = request('customer_order_id');
        $customerOrderPriceLogList = \App\Eloquent\Ygt\CustomerOrderPriceLog::where(['customer_order_id' => $customerOrderId])->get();

        $customerOrderPriceLogList = $customerOrderPriceLogList->map(function ($item) {
            //操作人用户名
            $tmpUid = $item->uid;
            $userInfo = DepartmentUser::getCurrentInfo($tmpUid)->toArray();
            $item['user_name'] = $userInfo['truename'];

            //操作类型
            $customerOrderPriceLogTypeList = config('customer-order-price-log-type');
            $item['type_name'] = $customerOrderPriceLogTypeList[$item->type];

            //操作时间
            $tmpRow = $item->toArray();
            $item['create_time'] = date('M-d H:i', $tmpRow['created_at']);

            //操作提示
            $item['operation_content'] = "修改为¥" . number_format($item->price, 2);

            return $item;
        });


        return $customerOrderPriceLogList;

    }

    //工单领材扫码验证
    public function getOrderReceiveMaterialCheck()
    {
//        $qrcodeStr = request('qrcode', '');
//        if (!$qrcodeStr) {
//            xThrow(ERR_PARAMETER);
//        }
//        $qrcodeArr = \App\Eloquent\Ygt\Qrcode::decodeStr($qrcodeStr, false);
//        if ($qrcodeArr == false) {
//            xThrow(ERR_UNKNOWN, '二维码类型出错');
//        }
//        $qrcodeId = $qrcodeArr['id'];
//        $qrcodeSn = $qrcodeArr['sn'];
//        $where = ['id' => $qrcodeId];
//        $qrcode = \App\Eloquent\Ygt\Qrcode::getInfo($where);
//        if (!$qrcode) {
//            xThrow(ERR_UNKNOWN, '二维码信息出错');
//        }
//        $productId = $qrcode->product_id;
//        $qrcodeInfo = [
//            'id' => $qrcode->id,
//            'sn' => $qrcode->sn,
//            'product_id' => $qrcode->product_id,
//            'stock_id' => $qrcode->stock_id,
//        ];
//        $where = ['id' => $productId];
//        $product = \App\Eloquent\Ygt\Product::getInfo($where);
//        if (!$product) {
//            xThrow(ERR_UNKNOWN, '材料信息出错');
//        }
//        $lists = [
//            ['left' => '材料名称', 'right' => $product->product_name],
//            ['left' => '材料编号', 'right' => $product->product_no],
//            ['left' => '堆位', 'right' => $product->place_name],
//        ];
//        //按钮
//        $buttonList = [
//            ['type' => 1, 'title' => '入库'],
//            ['type' => 2, 'title' => '出库'],
//            ['type' => 3, 'title' => '绑定'],
//            ['type' => 4, 'title' => '调度'],
//        ];
//        $result = [
//            'product_id' => $productId,
//            'lists' => $lists,
//            'button_list' => $buttonList,
//            'qrcode_info' => $qrcodeInfo,
//        ];

        //删除旧的领取记录
        $orderProcessId = request('order_process_id');
        $materialId = request('material_id');
        \App\Eloquent\Ygt\OrderMaterialQrLog::where(['order_process_course_id' => $orderProcessId, 'material_id' => $materialId,'type'=>4])->delete();

        return [
            'code' => 0,
            'message' => ''
        ];

//        return $result;

    }


    //工单领材扫码，获取码对应的详情（验证是否重复领取）
    public function getOrderReceiveMaterialQr()
    {
        $orderProcessId = request('order_process_id');
        $materialId = request('material_id');

        $qrcodeStr = request('qrcode', '');
        if (!$qrcodeStr) {
            xThrow(ERR_PARAMETER);
        }
        $qrcodeArr = \App\Eloquent\Ygt\Qrcode::decodeStr($qrcodeStr, false);
        if ($qrcodeArr == false) {
            xThrow(ERR_UNKNOWN, '二维码类型出错');
        }
        $qrcodeId = $qrcodeArr['id'];
        $qrcodeSn = $qrcodeArr['sn'];
        $where = ['id' => $qrcodeId];
        $qrcode = \App\Eloquent\Ygt\Qrcode::getInfo($where);
        if (!$qrcode) {
            xThrow(ERR_UNKNOWN, '二维码信息出错');
        }
        $productId = $qrcode->product_id;
        $qrcodeInfo = [
            'id' => $qrcode->id,
            'sn' => $qrcode->sn,
            'product_id' => $qrcode->product_id,
            'stock_id' => $qrcode->stock_id,
        ];
        $where = ['id' => $productId];
        $product = \App\Eloquent\Ygt\Product::getInfo($where);
        if (!$product) {
            xThrow(ERR_UNKNOWN, '材料信息出错');
        }

        //判断二维码是否在被使用
        if($qrcode['is_inuse']){
            return [
                'code' => 1,
                'message' => '该材料已被领取'
            ];
        }


        //判断是否是重复提交
        $orderMaterialQrLog = \App\Eloquent\Ygt\OrderMaterialQrLog::where(['order_process_course_id' => $orderProcessId, 'material_id' => $materialId, 'qr_id' => $qrcodeId, 'type' => 4])->first();
        if ($orderMaterialQrLog) {
            return [
                'code' => 1,
                'message' => '该材料已领取，请不要重复领取'
            ];
        }

        //数据添加到工序材料和扫码关联表
        $orderMaterialQrLogObj = \App\Eloquent\Ygt\OrderMaterialQrLog::firstOrNew(['id' => '']);
        $tmpInsertRow = [
            'order_process_course_id' => $orderProcessId,
            'material_id' => $materialId,
            'qr_id' => $qrcodeId,
            'num' => $qrcode->now_number,
            'type' => 4,
        ];
        $orderMaterialQrLogObj->fill($tmpInsertRow);
        $orderMaterialQrLogObj->save();


        $result = [
            'product_id' => $productId,
            'number' => $qrcode['now_number'] ? $qrcode['now_number'] : 1,
            'qr_id' => $qrcodeId,//所扫码的ID
        ];
        return $result;
    }




    //工单用料详情（余废退）扫码，获取码对应的详情（验证是否重复领取）|| 调整为只做验证作用
    public function getOrderSubmitMaterialQr()
    {
        $orderProcessId = request('order_process_course_id');
        $materialId = request('material_id');
        $type = request('type');

        $qrcodeStr = request('qrcode', '');
        if (!$qrcodeStr) {
            xThrow(ERR_PARAMETER);
        }
        $qrcodeArr = \App\Eloquent\Ygt\Qrcode::decodeStr($qrcodeStr, false);
        if ($qrcodeArr == false) {
            xThrow(ERR_UNKNOWN, '二维码类型出错');
        }
        $qrcodeId = $qrcodeArr['id'];
        $qrcodeSn = $qrcodeArr['sn'];
        $where = ['id' => $qrcodeId];
        $qrcode = \App\Eloquent\Ygt\Qrcode::getInfo($where);
        if (!$qrcode) {
            xThrow(ERR_UNKNOWN, '二维码信息出错');
        }
        $productId = $qrcode->product_id;
        $qrcodeInfo = [
            'id' => $qrcode->id,
            'sn' => $qrcode->sn,
            'product_id' => $qrcode->product_id,
            'stock_id' => $qrcode->stock_id,
        ];
        $where = ['id' => $productId];
        $product = \App\Eloquent\Ygt\Product::getInfo($where);
        if (!$product) {
            xThrow(ERR_UNKNOWN, '材料信息出错');
        }


        //判断是否是重复提交
        $orderMaterialQrLog = \App\Eloquent\Ygt\OrderMaterialQrLog::where(['order_process_course_id' => $orderProcessId, 'material_id' => $materialId, 'qr_id' => $qrcodeId, 'type' => $type])->first();
        if ($orderMaterialQrLog) {
            return [
                'code' => 1,
                'message' => '请不要扫重复的码'
            ];
        }

        $result = [
            'product_id' => $productId,
            'qr_id' => $qrcodeId,
            'number' => $qrcode['now_number'] ? $qrcode['now_number'] : 1,
        ];
        return $result;
    }

    //工单用料详情（余废退），提交具体数量
    public function getOrderSubmitMaterialNumber()
    {
        $orderProcessId = request('order_process_course_id');
        $materialId = request('material_id');
        $type = request('type');
        $qrId = request('qr_id');
        $num = request('num');


        //数据添加到工序材料和扫码关联表
        $orderMaterialQrLogObj = \App\Eloquent\Ygt\OrderMaterialQrLog::firstOrNew(['id' => '']);
        $tmpInsertRow = [
            'order_process_course_id' => $orderProcessId,
            'material_id' => $materialId,
            'qr_id' => $qrId,
            'type' => $type,
            'num' => $num,
        ];
        $orderMaterialQrLogObj->fill($tmpInsertRow);
        $orderMaterialQrLogObj->save();



        return [
            'code' => 0,
            'message' => '',//操作成功
        ];
    }


    


    //工单用料详情（余废退）扫码，清除之前的领取记录
    public function clearSubmitMaterialQrLog()
    {
//        $qrcodeStr = request('qrcode', '');
//        if (!$qrcodeStr) {
//            xThrow(ERR_PARAMETER);
//        }
//        $qrcodeArr = \App\Eloquent\Ygt\Qrcode::decodeStr($qrcodeStr, false);
//        if ($qrcodeArr == false) {
//            xThrow(ERR_UNKNOWN, '二维码类型出错');
//        }
//        $qrcodeId = $qrcodeArr['id'];
//        $qrcodeSn = $qrcodeArr['sn'];
//        $where = ['id' => $qrcodeId];
//        $qrcode = \App\Eloquent\Ygt\Qrcode::getInfo($where);
//        if (!$qrcode) {
//            xThrow(ERR_UNKNOWN, '二维码信息出错');
//        }
//        $productId = $qrcode->product_id;
//        $qrcodeInfo = [
//            'id' => $qrcode->id,
//            'sn' => $qrcode->sn,
//            'product_id' => $qrcode->product_id,
//            'stock_id' => $qrcode->stock_id,
//        ];
//        $where = ['id' => $productId];
//        $product = \App\Eloquent\Ygt\Product::getInfo($where);
//        if (!$product) {
//            xThrow(ERR_UNKNOWN, '材料信息出错');
//        }
//        $lists = [
//            ['left' => '材料名称', 'right' => $product->product_name],
//            ['left' => '材料编号', 'right' => $product->product_no],
//            ['left' => '堆位', 'right' => $product->place_name],
//        ];
//        //按钮
//        $buttonList = [
//            ['type' => 1, 'title' => '入库'],
//            ['type' => 2, 'title' => '出库'],
//            ['type' => 3, 'title' => '绑定'],
//            ['type' => 4, 'title' => '调度'],
//        ];
//        $result = [
//            'product_id' => $productId,
//            'lists' => $lists,
//            'button_list' => $buttonList,
//            'qrcode_info' => $qrcodeInfo,
//        ];

        $orderProcessCourseId = request('order_process_course_id');
        $materialId = request('material_id');
        $type = request('type');

        \App\Eloquent\Ygt\OrderMaterialQrLog::where(['order_process_course_id' => $orderProcessCourseId, 'material_id' => $materialId,'type'=>$type])->delete();


        return [
            'code' => 0,
            'message' => ''
        ];

//        return $result;

    }

    //订单反馈信息提交
    public function customerOrderFeedbackSubmit()
    {

        $userId = \App\Engine\Func::getHeaderValueByName('userid');
        $userInfo = \App\Eloquent\Ygt\DepartmentUser::getCurrentInfo($userId)->toArray();


        $id = request('id');
        $customerOrderId = request('customer_order_id');
        $desc = request('desc');

        //获得订单信息
        $customerOrderInfo = CustomerOrder::where('id','=',$customerOrderId)->first()->toArray();
        //获得顾客名
        $customerName = \App\Engine\OrderEngine::getOrderFiledValueTrue($customerOrderInfo['customer_name'], 18);


        $customerOrderFeedbackObj = \App\Eloquent\Ygt\CustomerOrderFeedback::firstOrNew(['customer_order_id'=>$customerOrderId,'id'=>$id]);
        $tmpInsertRow = [
            'customer_order_id' => $customerOrderId,
            'uid' => $userId,
            'desc' => $desc,
            'customer_name'=>$customerName
        ];
        $customerOrderFeedbackObj->fill($tmpInsertRow);
        $customerOrderFeedbackObj->save();

        //获取订单议价信息
        $customerOrderPrice = CustomerOrderPrice::where('customer_order_id','=',$customerOrderId)->first()->toArray();
        /*
         * "来源：客户
        主题：订单反馈
        内容：客户名称、单位名称、工艺名、品名、订单号、反馈信息"
        */

        $tmpCustomerOrderTitle = \App\Engine\Common::changeSnCode($customerOrderInfo['order_title']);
        $fieldName23 = \App\Engine\OrderEngine::getOrderFiledValueTrue($customerOrderInfo['field_name_23'], 19);
        $productName = \App\Engine\OrderEngine::getOrderFiledValueTrue($customerOrderInfo['product_name'], 20);
        //$customerName = \App\Engine\OrderEngine::getOrderFiledValueTrue($customerOrderInfo['customer_name'], 18);
        $orderTypeTitle = \App\Engine\OrderType::getOneValueById($customerOrderInfo['order_type'], 'title');//工艺名称


        $messageContent = "客户名:{$customerName}rnrn";
        $messageContent .= "单位名称:{$fieldName23}rnrn";
        $messageContent .= "工艺名:{$orderTypeTitle}rnrn";
        $messageContent .= "品名:{$productName}rnrn";
        $messageContent .= "订单号:{$tmpCustomerOrderTitle}rnrn";
        $messageContent .= "反馈信息:{$desc}rnrn";

        if($customerOrderPrice['sale_uid']){
            //给销售人员插入小秘书信息
            $data = [
                'company_id' => $customerOrderInfo['company_id'],//收消息人的企业ID
                'privilege_id' => '', //发消息给角色ID（批量用户），和‘to_user_id’只需填一个
                'form_user_id' => $userId,//发消息的用户ID
                'to_user_id' => $customerOrderPrice['sale_uid'],//发消息给的用户Id(单个用户)
                'foreign_key' => $customerOrderId,//外键，这里填订单ID
                'type' => 41,//消息类型，跳转到反馈列表type值需要新加
                'type_id' => $customerOrderId,//关联ID,用于跳转到反馈列表，这里应该填订单ID
                'title' => $customerOrderInfo['order_title'].'反馈信息',//消息标题
                'content' => $messageContent,//消息内容
                'theme' => '订单反馈',//主题
            ];
            \App\Eloquent\Ygt\UserMessage::sendCustomerOrderMessage($data);
        }

        if($customerOrderPrice['singleperson_uid']){
            //给下单人插入小秘书信息
            $data = [
                'company_id' => $customerOrderInfo['company_id'],//收消息人的企业ID
                'privilege_id' => '', //发消息给角色ID（批量用户），和‘to_user_id’只需填一个
                'form_user_id' => $userId,//发消息的用户ID
                'to_user_id' => $customerOrderPrice['singleperson_uid'],//发消息给的用户Id(单个用户)
                'foreign_key' => $customerOrderId,//外键，这里填订单ID
                'type' => 41,//消息类型，跳转到反馈列表type值需要新加
                'type_id' => $customerOrderId,//关联ID,用于跳转到反馈列表，这里应该填订单ID
                'title' => $customerOrderInfo['order_title'].'反馈信息',//消息标题
                'content' => $messageContent,//消息内容
                'theme' => '订单反馈',//主题
            ];
            \App\Eloquent\Ygt\UserMessage::sendCustomerOrderMessage($data);
        }

        return [
            'code' => 0,
            'message' => '提交成功',
        ];
    }

    //退货验证页面
    public function getReturnPurchaseFilterDetail()
    {
        //获取采购申请的详情
        $workFlowId = request('workflow_id');
        $rey = new \App\Repositories\OA\WorkflowRepository();
        $workflow = $rey->find(['id' => $workFlowId], ['workflowLogList.fileList']);
        $purchaseId = $workflow['related_id'];
        $purchaseRow = \App\Eloquent\Ygt\ReturnPurchase::where(['id' => $purchaseId])->first()->toArray();
        $purchaseMaterialList = \App\Eloquent\Ygt\ReturnPurchaseMaterial::where(['purchase_id' => $purchaseId])->get()->toArray();
        $materialList = [];
        $allSumMoney = '';//所有材料总价
        foreach ($purchaseMaterialList as $purchaseMaterialRow) {
            //获取材料名称
            $materialRow = \App\Engine\Product::getProductInfo($purchaseMaterialRow['material_id']);

            //追加材料图片地址
            $materialRow['img_url'] = '';
            if ($materialRow['img_id']) {
                $materialRow['img_url'] = \App\Eloquent\Ygt\ImgUpload::getImgUrlById($materialRow['img_id']);
            }


            //追加材料自定义属性
            $ProductFieldsModel = new \App\Eloquent\Ygt\ProductFields();
            $where = ['assemblage_material_id' => $materialRow['assemblage_material_id']];
            $productFields = \App\Eloquent\Ygt\ProductFields::where($where)->get();

            $productFields = $productFields->map(function ($item) {
                $data['field_name'] = $item->field_name;
                $data['is_compute'] = $item->is_compute;
                $comumnName = \App\Engine\Product::getFieldColumn($item->field_type);
                $data['field_value'] = $item->$comumnName;
                $data['unit'] = $item->unit;
                return $data;
            });

            //过滤计量属性
            $productFields = $productFields->toArray();
            foreach ($productFields as $key => $row){
                if($row['is_compute']){
                    unset($productFields[$key]);
                }
            }
            $productFields = array_values($productFields);

            $materialRow['custom_fields'] = $productFields;

            $firstText = $secondText = $thirdText = $fourthText = '';
            $fieldsArr = $productFields;
            if (!empty($fieldsArr)) {
                if (isset($fieldsArr[0])) {
                    $firstText = $fieldsArr[0]['field_name'] . ': ' . $fieldsArr[0]['field_value']. $fieldsArr[0]['unit'];
                }
                if (isset($fieldsArr[1])) {
                    $secondText = $fieldsArr[1]['field_name'] . ': ' . $fieldsArr[1]['field_value']. $fieldsArr[1]['unit'];
                }
                if (isset($fieldsArr[2])) {
                    $thirdText = $fieldsArr[2]['field_name'] . ': ' . $fieldsArr[2]['field_value']. $fieldsArr[2]['unit'];
                }
                if (isset($fieldsArr[3])) {
                    $fourthText = $fieldsArr[3]['field_name'] . ': ' . $fieldsArr[3]['field_value']. $fieldsArr[3]['unit'];
                }
            }

            //处理字段
//            $lists[$key]['first_text']   = $firstText;
//            $lists[$key]['second_text']  = $secondText;
//            $lists[$key]['third_text']   = $thirdText;


            $showMaterialRow = [
                'material_id' => $materialRow['id'],
                'product_name' => $materialRow['product_name'],
                'img_url' => $materialRow['img_url'],
                'custom_fields' => $materialRow['custom_fields'],
                'price' => $purchaseMaterialRow['price'],
                'num' => $purchaseMaterialRow['num'],
                'sum_money' => $purchaseMaterialRow['price'] * $purchaseMaterialRow['num'],//总价
                'first_text' => $firstText,//材料属性
                'second_text' => $secondText,//材料属性
                'third_text' => $thirdText,//材料属性
                'fourth_text' => $fourthText,//材料属性
            ];

            $allSumMoney += $showMaterialRow['sum_money'];

            $materialList[] = $showMaterialRow;
        }


        //获取供应商信息
        $supplierRow = \App\Eloquent\Ygt\SellerCompany::where(['id' => $purchaseRow['supplier_id']])->first();

        $supplierName = $supplierTel = '';
        if ($supplierRow) {
            $supplierName = $supplierRow['title'];
            $supplierTel = $supplierRow['contact_mobile'];
        }


        $userInfo = \App\Eloquent\Ygt\DepartmentUser::getCurrentInfo($purchaseRow['uid'])->toArray();//获取发起人信息


        $content = [
            'material_list' => $materialList,//采购材料名称（所有）
            'page_title' => $userInfo['truename'] . '退货单',//页面头部文字提示
            'name' => $userInfo['truename'],//供应商名称
            'tel' => $userInfo['mobile'],//供应商号码
            'date' => '',//交货日期
            'address' => '',//发货地址
        ];
        return $content;
    }


    //退货验证页面提交
    public function getReturnPurchaseFilterSubmit()
    {
        $userId = Func::getHeaderValueByName('userid');
        $userInfo = DepartmentUser::getCurrentInfo($userId)->toArray();
        $companyId = $userInfo['company_id'];

        $workFlowId = request('workflow_id');
        $materialIdArr = request('material_id_arr');

        $workFlowId = request('workflow_id');
        $rey = new \App\Repositories\OA\WorkflowRepository();
        $workflow = $rey->find(['id' => $workFlowId], ['workflowLogList.fileList']);


        $purchaseId = $workflow['related_id'];
        $purchaseRow = \App\Eloquent\Ygt\ReturnPurchase::where(['id' => $purchaseId])->first()->toArray();

        $materialIdList = [];
        $autoAddMaterialList = [];
        $priceAll = 0;
        if ($materialIdArr) {
            $materialIdList = explode(',', $materialIdArr);
            foreach ($materialIdList as $materialId) {
                $purchaseMaterialObj = \App\Eloquent\Ygt\ReturnPurchaseMaterial::where(['purchase_id' => $purchaseId, 'material_id' => $materialId])->first();
                if ($purchaseMaterialObj) {
                    if($purchaseMaterialObj->is_accept == 1){
                        return [
                            'code' => 1,
                            'message' => '材料已退货，请勿重复确认'
                        ];
                    }

                    $purchaseMaterialObj->is_accept = 1;
                    $purchaseMaterialObj->save();

                    $receiveMaterialUnitPrice = $purchaseMaterialObj->price ? $purchaseMaterialObj->price : 0;//单价
                    $receiveMaterialNumber = $purchaseMaterialObj->num;//材料数量

                    $priceAll += $receiveMaterialUnitPrice * $receiveMaterialNumber;
                }
            }
        } else {
            return [
                'code' => 1,
                'message' => '未选择材料'
            ];
        }

        //生成应收单
        $data = [
            'company_id'=>$purchaseRow['company_id'],
            'seller_company_id'=>$purchaseRow['supplier_id'],//厂的供应商id
            'money' => $priceAll,//金额
            'pay_type' => $purchaseRow['payment_method'] ? $purchaseRow['payment_method'] : '',//付款方式
            'add_user_id' => $purchaseRow['uid'],//添加人UID，调整为发起人的ID，否则对应的供应商账单将不显示
        ];
        $result = \App\Eloquent\Ygt\SellerBill::insertOneDataByType($data,'id',3);

        return '提交成功';
    }

    //工序管理员领取材料分次提交
    public function orderMaterialReceiveGradationSubmit(Request $request)
    {
        $userId = \App\Engine\Func::getHeaderValueByName('userid');
        $userInfo = \App\Eloquent\Ygt\DepartmentUser::getCurrentInfo($userId)->toArray();

        //获取传入数据
        $input = $request->all();
        $input['order_process_course_id'] = isset($input['order_process_course_id']) ? $input['order_process_course_id'] : '';
        $input['material_id'] = isset($input['material_id']) ? $input['material_id'] : '';//领取的材料id
        $input['receive_number'] = isset($input['receive_number']) ? $input['receive_number'] : '';//领取的材料数量
        $input['qr_ids'] = isset($input['qr_ids']) ? $input['qr_ids'] : '';//所扫码的ID集合


        //如果没有材料ID，取二维码对应的材料ID
        if(!$input['material_id']){
            if($input['qr_ids']) {
                $qrIdsArr = explode(',', $input['qr_ids']);
                $qrInfo = \App\Eloquent\Ygt\Qrcode::where(['id'=>$qrIdsArr[0]])->first();
                if($qrInfo){
                    $input['material_id'] = $qrInfo['product_id'];
                }
            }
        }



        //判断领取数量是否大于材料库存
//        $materialRow = \App\Engine\Product::getProductInfo($input['material_id']);
        //考虑集合材料的问题
        if(strstr($input['material_id'],'A')){
            $tmpAssemblageMaterialId = str_replace('A','',$input['material_id']);
            $materialRow = \App\Eloquent\Ygt\AssemblageMaterial::withTrashed()->where(['id'=>$tmpAssemblageMaterialId])->first();
        }else{
            $materialRow = ProductEngine::getProductInfo($input['material_id']);
        }

        if ($materialRow['number'] < $input['receive_number']) {
            return [
                'code' => 1,
                'message' => '库存不足' . "（现余库存{$materialRow['number']}）"
            ];
        }

        //逻辑调整传入的id实际为员工工单id
        $orderProcessCourseId = $input['order_process_course_id'];
        $orderProcessCourseRow = OrderProcessCourse::where(['id' => $orderProcessCourseId])->first()->toArray();

        //校验参数
        $rules = [
            'order_process_course_id' => 'required',
        ];
        $messages = [
            'order_process_course_id.required' => '缺少工单id',
        ];
        $this->validateRequestParameters($input, $rules, true, $messages);
        //获取对应工单工序表信息
        $orderProcessInfo = OrderProcess::where('id', $orderProcessCourseRow['order_process_id'])->first()->toArray();

        //工单材料表（修改操作，新加材料走其他接口）
        $orderMaterialCourseObj = OrderMaterialCourse::where(['order_process_course_id' => $orderProcessCourseId, 'process_type' => $orderProcessInfo['process_type'], 'material_id' => $input['material_id']])->first();
        $orderMaterialCourseObj->receive_number =$orderMaterialCourseObj->receive_number + $input['receive_number'];
        $orderMaterialCourseObj->save();

        //添加到分次提交表
        $orderMaterialReceiveGradationObj = \App\Eloquent\Ygt\OrderMaterialReceiveGradation::firstOrNew(['id'=>'']);
        $tmpInsertRow = [
            'order_process_course_id' => $orderProcessCourseId,
            'material_id' => $input['material_id'],
            'num' => $input['receive_number'],
            'uid' => $userId,
        ];
        $orderMaterialReceiveGradationObj->fill($tmpInsertRow);
        $orderMaterialReceiveGradationObj->save();

        //关联上分次领取记录和二维码的关系
        if($input['qr_ids']){
            $qrIdsArr = explode(',',$input['qr_ids']);
            $tmpObjList = \App\Eloquent\Ygt\OrderMaterialQrLog::where(['order_process_course_id'=>$orderProcessCourseId,'material_id'=>$input['material_id']])->whereIn('qr_id',$qrIdsArr)->get();
            foreach ($tmpObjList as $tmpObj){
                $tmpObj->order_material_recevie_gradation_id = $orderMaterialReceiveGradationObj->id;
                $tmpObj->save();
            }

            //已领取的对应的码做对应标记
            foreach ($qrIdsArr as $tmpQrId){
                if($tmpQrId){
                    $tmpQrcode = \App\Eloquent\Ygt\Qrcode::where(['id'=>$tmpQrId])->first();
                    if($tmpQrcode){
                        $tmpQrcode->now_number = 0;
                        $tmpQrcode->is_inuse = 1;
                        $tmpQrcode->save();
                    }
                }

            }
        }


        //材料出库
        Stock::OrderMaterialReceiveGradationStockOut($orderMaterialReceiveGradationObj->id);


        //如果工序订单状态为接单，修改状态
        $orderProcessId = $orderProcessInfo['id'];
        $orderProcessObj = OrderProcess::where(['id' => $orderProcessId])->first();
        if ($orderProcessObj->status == 1) {
            // 修改工序工单状态为2（已接单）
            $orderProcessObj->status = 2;
            $orderProcessObj->save();
        }



        ////发送消息给下单人领取情况
        //获取对应工单工序表信息
        $orderProcessInfo = OrderProcess::where('id', $orderProcessCourseRow['order_process_id'])->first()->toArray();
        $orderId = $orderProcessInfo['order_id'];
        $order = Order::where('id', $orderId)->first();
        $foreignKey = intval($order->customer_order_id);

        //判断用户是否为管理员
        $userInfo = DepartmentUser::getCurrentInfo($userId)->toArray();
        $companyId = isset($userInfo['company_id']) ? $userInfo['company_id'] : '';

        //获取材料名称
        $materialRow = \App\Engine\Product::getProductInfo($input['material_id']);

        //如果管理员是下单人，不发送消息
        if($userId != $order['uid']){
            $messageContent = '领取了材料'.$materialRow['product_name'].$input['receive_number'].$materialRow['unit'];
            $messageContent .= '【工单号: ' . $order['order_title'] . '】';
            $data = [
                'company_id' => $companyId,
                'privilege_id' => '',
                'form_user_id' => $userId,
                'to_user_id' => $order['uid'],
                'foreign_key' => $foreignKey,
                'type' => 32,//艺管理员领取材料时发送消息给下单人
                'type_id' => $orderProcessInfo['id'],
                'title' => $order['order_title'],
                'content' => $messageContent
            ];
            UserMessage::sendCustomerOrderMessage($data);
        }

        return [
            'code' => 0,
            'message' => '提交成功',
        ];

    }

    //领材确认领取界面，通过码的ID返回对应的材料信息
    public function getOrderMaterialConfirmReceive()
    {
        $qrIds = request('qr_ids');


        if($qrIds){
            $qrIdArr = explode(',',$qrIds);
        }


        //获取码ID对应的信息
        $qrInfoList = [];
        foreach ($qrIdArr as $qrId){
            if($qrId){
                $qrInfo = \App\Eloquent\Ygt\Qrcode::where(['id'=>$qrId])->first();
                if($qrInfo){
                    $qrInfoList[] = $qrInfo;
                }
            }
        }


        //按照材料ID分组
        $qrInfoDealList = [];
        foreach ($qrInfoList as $qrInfo){
            if(isset($qrInfoDealList[$qrInfo['product_id']])){
                $qrInfoDealList[$qrInfo['product_id']]['receive_number'] ++;
                $qrInfoDealList[$qrInfo['product_id']]['receive_number_tips'] = "共计{$qrInfoDealList[$qrInfo['product_id']]['receive_number']}件";
                $qrInfoDealList[$qrInfo['product_id']]['qr_list'][] = $qrInfo;
            }else{
                //获取材料名称
                $materialName = "";
                $tmpObj = \App\Eloquent\Ygt\Product::where(['id'=>$qrInfo['product_id']])->first();
                if($tmpObj){
                    $materialName = $tmpObj->product_name;
                }

                $qrInfoDealList[$qrInfo['product_id']] = [
                    'material_id' => $qrInfo['product_id'],
                    'material_name' => $materialName,
                    'receive_number' => 1,
                    'receive_number_tips' => '共计1件',
                    'qr_list' => [
                        $qrInfo,
                    ],
                ];
            }
        }

        //转为索引数组
        $qrInfoDealList = array_values($qrInfoDealList);


        return $qrInfoDealList;
    }

    //采购申请选择材料获取材料详情
    public function getPurchaseMaterialInfo()
    {
        $materialIds = request('material_ids');
        $materialIdArr = [];
        if($materialIds){
            $materialIdArr = explode(',',$materialIds);
        }

        $materialList = [];
        foreach ($materialIdArr as $materialId){
            if($materialId){
                //如果是集合材料需要另外处理
                if(strstr($materialId,'A')){
                    $tmpAssemblageMaterialId = str_replace('A','',$materialId);
                    $materialRow = \App\Eloquent\Ygt\AssemblageMaterial::withTrashed()->where(['id'=>$tmpAssemblageMaterialId])->first();
                    if(!$materialRow){
                        continue;
                    }

                    $materialRow['seller_company_id'] = -1;//未选择供应商材料

                    //集合材料相关的供应商
                    $tmpProductList = \App\Eloquent\Ygt\Product::where(['assemblage_material_id'=>$tmpAssemblageMaterialId])->get();
                    $supplierList = [];
                    foreach ($tmpProductList as $tmpProductRow){
                        $sellerCompanyId = $tmpProductRow['seller_company_id'];
                        //获取供应商信息
                        $tmpSellerCompanyRow = \App\Eloquent\Ygt\SellerCompany::where(['id'=>$sellerCompanyId])->first();
                        if($tmpSellerCompanyRow){
                            $supplierList[]=[
                                'seller_company_title' => $tmpSellerCompanyRow['title'],
                                'material_id' => $tmpProductRow['id'],
                                'number'=> $tmpProductRow['number'].$tmpProductRow['unit'],
                                'y_number'=>'0'.$tmpProductRow['unit'],
                                'price'=>'￥'.$tmpProductRow['price'],
                            ];
                        }
                    }
                    $materialRow['supplier_list'] = $supplierList;


                    //追加材料自定义属性
                    $ProductFieldsModel = new \App\Eloquent\Ygt\ProductFields();
                    $where = ['assemblage_material_id' => $materialRow['id']];
                    $productFields = \App\Eloquent\Ygt\ProductFields::where($where)->get();

                    $productFields = $productFields->map(function ($item) {
                        $data['field_name'] = $item->field_name;
                        $data['is_compute'] = $item->is_compute;
                        $comumnName = \App\Engine\Product::getFieldColumn($item->field_type);
                        $data['field_value'] = $item->$comumnName;
                        $data['unit'] = $item->unit;
                        return $data;
                    });

                    //过滤计量属性
                    $productFields = $productFields->toArray();
                    foreach ($productFields as $key => $row){
                        if($row['is_compute']){
                            unset($productFields[$key]);
                        }
                    }
                    $productFields = array_values($productFields);


                    $fieldsList         = $productFields;
                    $firstText = $secondText = $thirdText ='';
                    if(!empty($fieldsList))
                    {
                        if(isset($fieldsList[0]))
                        {
                            $firstText   = $fieldsList[0]['field_name'].': '.$fieldsList[0]['field_value'].$fieldsList[0]['unit'];
                        }
                        if(isset($fieldsList[1]))
                        {
                            $secondText  = $fieldsList[1]['field_name'].': '.$fieldsList[1]['field_value'].$fieldsList[1]['unit'];
                        }
                        if(isset($fieldsList[2]))
                        {
                            $thirdText   = $fieldsList[2]['field_name'].': '.$fieldsList[2]['field_value'].$fieldsList[2]['unit'];
                        }
                    }
                    $customFieldsText                       = $firstText.' '.$secondText.' '.$thirdText;
                    $materialRow['custom_fields']        = $fieldsList;
                    $materialRow['first_text']           = $firstText;
                    $materialRow['second_text']          = $secondText;
                    $materialRow['third_text']           = $thirdText;
                    $materialRow['custom_fields_text']   = $customFieldsText;
                    $materialRow['custom_fields'] = $productFields;

                    //追加材料图片地址
                    $materialRow['img_url'] = '';
                    if ($materialRow['img_id']) {
                        $materialRow['img_url'] = \App\Eloquent\Ygt\ImgUpload::getImgUrlById($materialRow['img_id']);
                    }


                    if(!isset($materialList[$materialRow['seller_company_id']])){
                        $materialList[$materialRow['seller_company_id']]['supllier_name'] = '未选择供应商';
                        $materialList[$materialRow['seller_company_id']]['pay_method'] = '无';
                        $materialList[$materialRow['seller_company_id']]['supllier_id'] = $materialRow['seller_company_id'];
                        $materialList[$materialRow['seller_company_id']]['is_unselected'] = 1;
                    }

                    //添加材料信息
                    $materialRow = $materialRow->toArray();
                    $materialRow['id'] = "A".$materialRow['id'];

                    $materialList[$materialRow['seller_company_id']]['material_list'][] = $materialRow;

                }else{
                    //获取材料信息
                    $materialRow = \App\Eloquent\Ygt\Product::where(['id'=>$materialId])->first();
                    if(!$materialRow){
                        continue;
                    }

                    //追加材料自定义属性
                    $ProductFieldsModel = new \App\Eloquent\Ygt\ProductFields();
                    $where = ['assemblage_material_id' => $materialRow['assemblage_material_id']];
                    $productFields = \App\Eloquent\Ygt\ProductFields::where($where)->get();

                    $productFields = $productFields->map(function ($item) {
                        $data['field_name'] = $item->field_name;
                        $data['is_compute'] = $item->is_compute;
                        $comumnName = \App\Engine\Product::getFieldColumn($item->field_type);
                        $data['field_value'] = $item->$comumnName;
                        $data['unit'] = $item->unit;
                        return $data;
                    });

                    //过滤计量属性
                    $productFields = $productFields->toArray();
                    foreach ($productFields as $key => $row){
                        if($row['is_compute']){
                            unset($productFields[$key]);
                        }
                    }
                    $productFields = array_values($productFields);


                    $fieldsList         = $productFields;
                    $firstText = $secondText = $thirdText ='';
                    if(!empty($fieldsList))
                    {
                        if(isset($fieldsList[0]))
                        {
                            $firstText   = $fieldsList[0]['field_name'].': '.$fieldsList[0]['field_value'].$fieldsList[0]['unit'];
                        }
                        if(isset($fieldsList[1]))
                        {
                            $secondText  = $fieldsList[1]['field_name'].': '.$fieldsList[1]['field_value'].$fieldsList[1]['unit'];
                        }
                        if(isset($fieldsList[2]))
                        {
                            $thirdText   = $fieldsList[2]['field_name'].': '.$fieldsList[2]['field_value'].$fieldsList[2]['unit'];
                        }
                    }
                    $customFieldsText                       = $firstText.' '.$secondText.' '.$thirdText;
                    $materialRow['custom_fields']        = $fieldsList;
                    $materialRow['first_text']           = $firstText;
                    $materialRow['second_text']          = $secondText;
                    $materialRow['third_text']           = $thirdText;
                    $materialRow['custom_fields_text']   = $customFieldsText;
                    $materialRow['custom_fields'] = $productFields;

                    //追加材料图片地址
                    $materialRow['img_url'] = '';
                    if ($materialRow['img_id']) {
                        $materialRow['img_url'] = \App\Eloquent\Ygt\ImgUpload::getImgUrlById($materialRow['img_id']);
                    }

                    //按供应商分类
                    if(!$materialRow['seller_company_id']){
                        $materialRow['seller_company_id'] = 0;//本厂材料
                    }


                    if(!isset($materialList[$materialRow['seller_company_id']])){
                        if($materialRow['seller_company_id'] == 0){
                            $materialList[$materialRow['seller_company_id']]['supllier_name'] = '本厂材料';
                            $materialList[$materialRow['seller_company_id']]['pay_method'] = '无';
                            $materialList[$materialRow['seller_company_id']]['supllier_id'] = 0;
                            $materialList[$materialRow['seller_company_id']]['is_unselected'] = 0;
                            $materialList[$materialRow['seller_company_id']]['number']=$materialRow['number'].$materialRow['unit'];
                            $materialList[$materialRow['seller_company_id']]['y_number']='0'.$materialRow['unit'];
                            $materialList[$materialRow['seller_company_id']]['price']='0'.$materialRow['price'];
                        }else{
                            //获取供应商信息
                            $supllierRow = \App\Eloquent\Ygt\SellerCompany::where(['id'=>$materialRow['seller_company_id']])->first();
                            if($supllierRow){
                                $materialList[$materialRow['seller_company_id']]['supllier_name'] = $supllierRow['title'];
                                $materialList[$materialRow['seller_company_id']]['pay_method'] = $supllierRow['pay_type'];
                                $materialList[$materialRow['seller_company_id']]['supllier_id'] = $materialRow['seller_company_id'];
                                $materialList[$materialRow['seller_company_id']]['is_unselected'] = 0;
                                $materialList[$materialRow['seller_company_id']]['number']=$materialRow['number'].$materialRow['unit'];
                                $materialList[$materialRow['seller_company_id']]['y_number']='0'.$materialRow['unit'];
                                $materialList[$materialRow['seller_company_id']]['price']='0'.$materialRow['price'];
                            }else{
                                $materialList[$materialRow['seller_company_id']]['supllier_name'] = '未知供应商';
                                $materialList[$materialRow['seller_company_id']]['pay_method'] = '无';
                                $materialList[$materialRow['seller_company_id']]['supllier_id'] = $materialRow['seller_company_id'];
                                $materialList[$materialRow['seller_company_id']]['is_unselected'] = 0;
                                $materialList[$materialRow['seller_company_id']]['number']=$materialRow['number'].$materialRow['unit'];
                                $materialList[$materialRow['seller_company_id']]['y_number']='0'.$materialRow['unit'];
                                $materialList[$materialRow['seller_company_id']]['price']='0'.$materialRow['price'];
                            }
                        }
                    }

                    //添加材料信息
                    $materialList[$materialRow['seller_company_id']]['material_list'][] = $materialRow;
                }
            }
        }

        //把未选择材料的供应商放到最后
        if(isset($materialList[-1])){
            $tmpArr = $materialList[-1];
            unset($materialList[-1]);
            $materialList = array_values($materialList);
            //如果版本号小于1.3.1 不返回未选择供应商的数据
            //获取版本号
            $version = request()->header('version');
            if($version && ($version >= '1.3.1')){
                $materialList[] = $tmpArr;
            }

        }else{
            $materialList = array_values($materialList);
        }

        return $materialList;
    }


    //成品入库验收界面
    public function getFinishedProductCheck()
    {
        $orderFinishedProductId = request('id');
        $orderFinishedProductRow = \App\Eloquent\Ygt\OrderFinishedProduct::where(['id'=>$orderFinishedProductId])->first();

        //获取员工名称和头像
        $userInfo  = \App\Eloquent\Ygt\User::getInfo( ['id'=>$orderFinishedProductRow['uid']]);
        $avatarUrl             = \App\Eloquent\Ygt\ImgUpload::getOneValueById( $userInfo['avatar'], 'img_url' );
        if( $avatarUrl ){
            $avatarHttp        = \App\Engine\Func::getImgUrlHttp( $avatarUrl );
        } else {
            $avatarHttp        = asset('upload/appicon/logo.png');
        }

        //工艺名称，工单号，数量，规格
        $orderId = $orderFinishedProductRow['order_id'];
        $orderRow = \App\Eloquent\Ygt\Order::where(['id'=>$orderId])->first();

        $orderTypeTitle        = \App\Engine\OrderType::getOneValueById($orderRow['order_type'], 'title');//工艺名称

        //成品规格数据处理
        if (isset($orderRow['finished_specification'])) {
            $tmpArr = explode(',', $orderRow['finished_specification']);
            if (count($tmpArr) == 2) {
                $orderRow['finished_specification'] = sprintf("%s×%s厘米", $tmpArr[0], $tmpArr[1]);
            }

            if (count($tmpArr) == 3) {
                $orderRow['finished_specification'] = sprintf("%s×%s×%s厘米", $tmpArr[0], $tmpArr[1], $tmpArr[2]);
            }

            //如果数据都为空，显示为空
            $hasData = false;
            foreach ($tmpArr as $tmpValue) {
                if ($tmpValue) {
                    $hasData = true;
                }
            }

            if (!$hasData) {
                $orderRow['finished_specification'] = '';
            }
        }

        $orderRow['order_title'] = \App\Engine\Common::changeSnCode($orderRow['order_title']);

        $isAbleWarehousing = 0;//能否入库
        if($orderFinishedProductRow['status'] == 1){
            $isAbleWarehousing = 1;
        }

        $customFieldsText = '';
        if($orderRow['finished_weight'] && $orderFinishedProductRow['number']){
            $finished_weight_arr = explode(',',$orderRow['finished_weight']);
            $weightAll = $finished_weight_arr[0] * $orderFinishedProductRow['number'];
            if($weightAll){
                //重量转换 zhuyujun 20190109
                $weightAll = \App\Engine\Common::weightDeal($weightAll);
                $customFieldsText = "重量：{$weightAll}";
            }
        }

        if($orderRow['product_num']){
            $product_num_arr = explode(',',$orderRow['product_num']);
            $orderRow['unit'] = $product_num_arr[1];
        }


        //获取工单的示例图
        //获取生产实例图
        $productionCaseDiagram = \App\Engine\OrderEngine::getOrderFiledValueTrue($orderRow['production_case_diagram'], 9);

        $productInfo = BuyersProduct::where('id','=',$orderRow['product_name'])->first();
        $product_name = '';
        if($productInfo){
            $productInfo = $productInfo->toArray();
            $product_name = $productInfo['name'];
        }
        $re = [
            'truename' => $userInfo['truename'],
            'avatar_http' => $avatarHttp,
            'order_title' => $orderRow['order_title'],
            'order_type_title' => $orderTypeTitle,
            'finished_specification' => $orderRow['finished_specification'],
            'number' => $orderFinishedProductRow['number'],
            'unit'=>$orderRow['unit'],
            'custom_fields_text' => $customFieldsText,
            'production_case_diagram' => $productionCaseDiagram,
            'is_able_warehousing' => $isAbleWarehousing,
            'product_name'=>$product_name,
        ];

        return $re;

    }

    //成品入库验收提交
    public function finishedProductCheckSubmit()
    {
        $orderFinishedProductId = request('order_finished_product_id');
        $number = request('number');
        $placeName = request('place_name');

        $orderFinishedProductRow = \App\Eloquent\Ygt\OrderFinishedProduct::where(['id'=>$orderFinishedProductId])->first();



        $orderId = $orderFinishedProductRow['order_id'];
        $orderRow = \App\Eloquent\Ygt\Order::where(['id'=>$orderId])->first();

        if(!$number){
            return [
                'code' => 1,
                'message' => '未填写数量',
            ];
        }else if ($number < $orderFinishedProductRow['number']){
            //2019-01-23 Linwei 如果确认入库数量少于待入库数量，则做拆分
            $orderFinishedProductRow_copy=[];
            $orderFinishedProductRow_copy['order_id']=$orderFinishedProductRow['order_id'];
            $orderFinishedProductRow_copy['order_process_id']=$orderFinishedProductRow['order_process_id'];
            $orderFinishedProductRow_copy['order_process_course_id']=$orderFinishedProductRow['order_process_course_id'];
            $orderFinishedProductRow_copy['uid']=$orderFinishedProductRow['uid'];
            $orderFinishedProductRow_copy['status']=$orderFinishedProductRow['status'];
            $orderFinishedProductRow_copy['relate_id']=$orderFinishedProductRow['relate_id'];
            $orderFinishedProductRow_copy['company_id']=$orderFinishedProductRow['company_id'];
            $orderFinishedProductRow_copy['created_at']=time();
            $orderFinishedProductRow_copy['updated_at']=time();
            $orderFinishedProductRow_copy['number'] =$orderFinishedProductRow['number']-$number;
            \App\Eloquent\Ygt\OrderFinishedProduct::insert($orderFinishedProductRow_copy);
        }

        //成品入库
//        $userId = $orderFinishedProductRow['uid'];
        //消息发送人还是用登陆用户的uid zhuyujun 20181205
        //获取登陆用户信息
        $userId = \App\Engine\Func::getHeaderValueByName('userid');
        $userInfo = \App\Eloquent\Ygt\DepartmentUser::getCurrentInfo($userId)->toArray();

        $relateId = \App\Engine\WarehouseEngine::insertOneData($userId, $orderId, $number,$placeName);

        if($orderFinishedProductRow->status == 2){
//            return [
//                'code' => 1,
//                'message' => '请勿重复入库',
//            ];
        }

        //修改状态&关联ID
        $orderFinishedProductRow->status = 2;
        $orderFinishedProductRow->relate_id = $relateId;
        $orderFinishedProductRow->save();



//        //发送消息给发货员
//        $orderRow = \App\Eloquent\Ygt\Order::where(['id' => $orderId])->first();
//        $companyId = $orderRow['company_id'];
//        $foreignKey = $orderRow['customer_order_id'];
//        $privilegeIdList = \App\Engine\OrderEngine::getPrivilegeByNode($companyId, 14);
//
//        foreach ($privilegeIdList as $privilegeId) {
//            if ($privilegeId) {
//                $data = [
//                    'company_id' => $companyId,
//                    'privilege_id' => $privilegeId,
//                    'form_user_id' => $userId,
//                    'to_user_id' => '',
//                    'foreign_key' => $foreignKey,
//                    'type' => 34,
//                    'type_id' => $orderId,
//                    'title' => $orderRow['order_title'],
//                    'content' => '工单有新的成品入库了'
//                ];
//                UserMessage::sendCustomerOrderMessage($data);
//            }
//        }


        return '操作成功';
    }

    //获取用料提交历史记录
    public function materialSubmitHistory()
    {
        $orderProcessId = request('order_process_id');
        //获取列表
        $tmpOrderProcessMaterialSubmitList = \App\Eloquent\Ygt\OrderProcessMaterialSubmit::where(['order_process_id'=>$orderProcessId])->orderBy('id','desc')->get();
        $materialSubmitHistoryList = [];
        foreach ($tmpOrderProcessMaterialSubmitList as $tmpOrderProcessMaterialSubmitListRow){
            $tmpOrderProcessMaterialSubmitId = $tmpOrderProcessMaterialSubmitListRow['id'];

            //操作员信息
            $tmpUserInfo = \App\Eloquent\Ygt\DepartmentUser::getCurrentInfo($tmpOrderProcessMaterialSubmitListRow['uid'])->toArray();
            $operationName = $tmpUserInfo['truename'];
            //操作时间
            $tmpArr = $tmpOrderProcessMaterialSubmitListRow->toArray();
            $operationTime = date('Ymd H:i:s',$tmpArr['created_at']);


            $tmpOrderProcessMaterialSubmitList = \App\Eloquent\Ygt\OrderProcessMaterialSubmitDetail::where(['order_process_material_submit_id'=>$tmpOrderProcessMaterialSubmitId])->get();
            $tmpList = [];
            foreach ($tmpOrderProcessMaterialSubmitList as $tmpOrderProcessMaterialSubmitRow){
                //获取名称
                $tmpName = '';
                $unit = 'kg';
                $customer_name = '';
                $supplier_name = '';
                $custom_fields_text = '';
                $img_url = '';

                if($tmpOrderProcessMaterialSubmitRow['type'] == 1){
                    $tmpMaterialRow =  \App\Eloquent\Ygt\Product::where(['id'=>$tmpOrderProcessMaterialSubmitRow['relate_id']])->first();
                    if($tmpMaterialRow){
                        $tmpName = $tmpMaterialRow['product_name'];
                        $unit = $tmpMaterialRow['unit'];
                        //补齐 供应商 归属人 属性
                        if($tmpMaterialRow['customer_id']){
                            $customer_name = \App\Eloquent\Ygt\Customer::getOneValueById($tmpMaterialRow['customer_id'],'customer_name');
                        }

                        if($tmpMaterialRow['seller_company_id']){
                            $supplier_name = \App\Eloquent\Ygt\SellerCompany::getOneValueById($tmpMaterialRow['seller_company_id'],'title');
                        }

                        if($tmpMaterialRow['assemblage_material_id']){
                            $tempAttrList = \App\Engine\Material::getMaterialField($tmpMaterialRow['assemblage_material_id']);
                            $custom_fields_text = $tempAttrList['custom_fields_text'];
                        }

                        if($tmpMaterialRow['img_id']){
                            $img_url = ImgUpload::getImgUrlById($tmpMaterialRow['img_id']);
                        }
                    }
                }elseif($tmpOrderProcessMaterialSubmitRow['type'] == 2){
                    $tmpWasterRow = \App\Eloquent\Ygt\OrdertypeProcessWaste::where(['id'=>$tmpOrderProcessMaterialSubmitRow['relate_id']])->first();
                    if($tmpWasterRow){
                        $tmpName = $tmpWasterRow['title'];
                    }
                }

                $tmpList[] = [
                    'name' => $tmpName,
                    'type' => $tmpOrderProcessMaterialSubmitRow['type'],
                    'relate_id' => $tmpOrderProcessMaterialSubmitRow['relate_id'],
                    'residual_number' => $tmpOrderProcessMaterialSubmitRow['residual_number'].$unit,
                    'scrap_number' => $tmpOrderProcessMaterialSubmitRow['scrap_number'].$unit,
                    'retreat_number' => $tmpOrderProcessMaterialSubmitRow['retreat_number'].$unit,
                    'place_name' => $tmpOrderProcessMaterialSubmitRow['place_name'],
                    'customer_name' => $customer_name,
                    'supplier_name' => $supplier_name,
                    'custom_fields_text' => $custom_fields_text,
                    'img_url' =>$img_url,
                ];
            }

            $materialSubmitHistoryList[] = [
                'order_process_material_submit_id' => $tmpOrderProcessMaterialSubmitId,
                'operation_name' => $operationName,
                'operation_time' => $operationTime,
                'list' => $tmpList,
            ];
        }

        return $materialSubmitHistoryList;

    }







    //获取工单列表筛选状态列表
    public function getOrderListFilterStatus()
    {
        $orderListFilterStatus = [
            [
                'title' => '全部',
                'value' => '',
            ],
            [
                'title' => '待开工',
                'value' => '1',
            ],
            [
                'title' => '进行中',
                'value' => '2',
            ],
            [
                'title' => '已完成',
                'value' => '3',
            ]
        ];

        return $orderListFilterStatus;
    }


    //工单基础页面字段
    public function orderBaseFieldList()
    {
        return [
            [
                'field_name' => 'customer_name',
                'title' => '客户',
                'field_type' => 1,
                'placeholder' => '请填写',
                'relation_id' => '',
                'is_must' => 0,
                'field_unit' => [],
                'data' => [],
            ],
            [
                'field_name' => 'product_name',
                'title' => '品名',
                'field_type' => 1,
                'placeholder' => '请填写',
                'relation_id' => '',
                'is_must' => 0,
                'field_unit' => [],
                'data' => [],
            ],
            [
                'field_name' => 'contract_number',
                'title' => '合同编号',
                'field_type' => 1,
                'placeholder' => '请填写',
                'relation_id' => '',
                'is_must' => 0,
                'field_unit' => [],
                'data' => [],
            ],
//            [
//                'field_name' => 'enterprise_icon',
//                'title' => '企业图标',
//                'field_type' => 9,
//                'placeholder' => '请上传',
//                'new_page_title' => '上传企业图标',
//                'relation_id' => '',
//                'is_must' => 0,
//                'field_unit' => [],
//                'data' => [],
//            ],
            [
                'field_name' => 'finished_date',
                'title' => '交货日期',
                'field_type' => 7,
                'placeholder' => '请填写',
                'relation_id' => '',
                'is_must' => 0,
                'field_unit' => [],
                'data' => [],
            ],
            [
                'field_name' => 'add_distribution_address',
                'title' => '添加配送地址',
                'field_type' => 8,
                'placeholder' => '请填写',
                'relation_id' => '',
                'is_must' => 0,
                'field_unit' => [],
                'data' => [],
            ],
            [
                'field_name' => 'product_num',
                'title' => '下单数量',
                'field_type' => 5,
                'placeholder' => '请填写',
                'relation_id' => '',
                'is_must' => 0,
                'field_unit' => [
                    [
                        'id' => 1,
                        'title' => '米'
                    ],
                    [
                        'id' => 2,
                        'title' => '条'
                    ]
                ],
                'data' => [],
            ],
//            [
//                'field_name' => 'chip_specification_length',
//                'title' => '片料规格-长',
//                'field_type' => 1,
//                'placeholder' => '请填写',
//                'relation_id' => '',
//                'is_must' => 0,
//                'field_unit' => [],
//                'data' => [],
//            ],
//            [
//                'field_name' => 'chip_specification_width',
//                'title' => '片料规格-宽',
//                'field_type' => 1,
//                'placeholder' => '请填写',
//                'relation_id' => '',
//                'is_must' => 0,
//                'field_unit' => [],
//                'data' => [],
//            ],
//            [
//                'field_name' => 'grammage',
//                'title' => '克数',
//                'field_type' => 1,
//                'placeholder' => '请填写',
//                'relation_id' => '',
//                'is_must' => 0,
//                'field_unit' => [],
//                'data' => [],
//            ],
//            [
//                'field_name' => 'weaving_type',
//                'title' => '织布类型',
//                'field_type' => 1,
//                'placeholder' => '请填写',
//                'relation_id' => '',
//                'is_must' => 0,
//                'field_unit' => [],
//                'data' => [],
//            ],
//            [
//                'field_name' => 'plate_numbering',
//                'title' => '印版编号',
//                'field_type' => 1,
//                'placeholder' => '请填写',
//                'relation_id' => '',
//                'is_must' => 0,
//                'field_unit' => [],
//                'data' => [],
//            ],
//            [
//                'field_name' => 'plate_position',
//                'title' => '印版位置',
//                'field_type' => 1,
//                'placeholder' => '请填写',
//                'relation_id' => '',
//                'is_must' => 0,
//                'field_unit' => [],
//                'data' => [],
//            ],
//            [
//                'field_name' => 'public_plate',
//                'title' => '公用印版',
//                'field_type' => 1,
//                'placeholder' => '请填写',
//                'relation_id' => '',
//                'is_must' => 0,
//                'field_unit' => [],
//                'data' => [],
//            ],
//            [
//                'field_name' => 'plate_modification',
//                'title' => '印版修改',
//                'field_type' => 1,
//                'placeholder' => '请填写',
//                'relation_id' => '',
//                'is_must' => 0,
//                'field_unit' => [],
//                'data' => [],
//            ],
//            [
//                'field_name' => 'finished_weight',
//                'title' => '成品重量',
//                'field_type' => 1,
//                'placeholder' => '请填写',
//                'relation_id' => '',
//                'is_must' => 0,
//                'field_unit' => [],
//                'data' => [],
//            ],
            [
                'field_name' => 'is_priority',
                'title' => '优先处理',
                'field_type' => 6,
                'placeholder' => '',
                'relation_id' => '',
                'is_must' => 0,
                'field_unit' => [],
                'data' => [],
            ],
            [
                'field_name' => 'production_case_diagram',
                'title' => '生产实例图',
                'field_type' => 9,
                'placeholder' => '请上传',
                'new_page_title' => '上传企业图标',
                'relation_id' => '',
                'is_must' => 0,
                'field_unit' => [],
                'data' => [],
            ]
        ];
    }

    public function getUnitIdByTitle($unitTitle, $unitList)
    {
        foreach ($unitList as $unitRow) {
            if ($unitRow['title'] == $unitTitle) {
                return $unitRow['id'];
            }
        }
        return false;
    }

    public function getSidByTitle($dataTitle, $dataList)
    {
        foreach ($dataList as $dataRow) {
            if ($dataRow['title'] == $dataTitle) {
                return $dataRow['id'];
            }
        }
        return false;
    }

    public function getProcessCourseInfoWithList()
    {
        $orderProcessId = request('order_process_id');

        $order_process_info = OrderProcess::where('id', $orderProcessId)->first();

        $processTitle = Process::getOneValueById($order_process_info['process_type'], 'title');

        $statusArray = [
            '1' => '待接单',
            '2' => '待分派',
            '3' => '生产中',
            '4' => '已完成',
            '101' => '待开工',
        ];
        $processStatusStr = $statusArray[$order_process_info['status']];
        $processInfoStr = $processStatusStr . '[' . $processTitle . ']';

        $orderinfo = $this->info($order_process_info->order_id);

        ////替换产品名称为工序类型名称
        //获取工序类型名称
        $orderTypeTitle = OrderType::getOneValueById($orderinfo['order_type'], 'title');
        $orderinfo['product_name'] = $orderTypeTitle;

        $list = OrderProcessCourse::getAllWithUser($orderProcessId, $order_process_info['company_id']);

        //增加限制
        $userId = Func::getHeaderValueByName('userid');
        foreach ($list as &$row) {
            $row['is_allow_write'] = 0;
            if ($userId == $order_process_info['uid']) {//允许
                $row['is_allow_write'] = 1;
            }
        }


        $courseStatusArray = [
            '1' => '待开工',
            '2' => '待领取材料',
            '3' => '生产中',
            '4' => '已完成',
        ];
        $list->transform(function ($item) use ($courseStatusArray) {
            $item->statusStr = $courseStatusArray[$item->status];
            $item->creat_time = $item->created_at->formatLocalized('%Y-%m-%d');
            if (!$item->waste_number) {
                $item->waste_number = 0;
            }
            return $item;
        });


        //统计工序完成数量
        $processIsSum = Process::getOneValueById($order_process_info['process_type'], 'is_sum');

        $tmpUserList = [];
        $finishUserNumList = [];
        //员工分组，按角色分类
        $allMoney = 0;//总计件工资
        $finishNum = 0;//总完成数量
        foreach ($list as $tmpRow) {
            $tmpUid = $tmpRow->uid;

            //获取用户id对应角色id
            $tmpUserInfo = DepartmentUser::getCurrentInfo($tmpUid)->toArray();
            $tmpPrivilegeId = $tmpUserInfo['privilege_id'];
            $tmpPrivilegeTitle = Privilege::getOneValueById($tmpPrivilegeId, 'title');

            $tmpRow->price = $tmpUserInfo['price'];
            $tmpRow->money = $tmpUserInfo['price'] * $tmpRow['finish_number'];

            if (isset($tmpUserList[$tmpPrivilegeId])) {
                $tmpUserList[$tmpPrivilegeId]['sumNumber'] += $tmpRow->finish_number;//同角色总数量
                $tmpUserList[$tmpPrivilegeId]['sumMoney'] += $tmpRow->finish_number * $tmpRow->price;//同角色总计件工资
                $tmpUserList[$tmpPrivilegeId]['sumUserNum']++;//同角色总人数

                $tmpUserList[$tmpPrivilegeId]['userList'][] = $tmpRow;
                $allMoney += $tmpRow->finish_number * $tmpRow->price;
            } else {
                $tmpUserList[$tmpPrivilegeId]['privilegeId'] = $tmpPrivilegeId;
                $tmpUserList[$tmpPrivilegeId]['privilegeTitle'] = $tmpPrivilegeTitle;
                $tmpUserList[$tmpPrivilegeId]['sumNumber'] = $tmpRow->finish_number;
                $tmpUserList[$tmpPrivilegeId]['sumMoney'] = $tmpRow->finish_number * $tmpRow->price;
                $tmpUserList[$tmpPrivilegeId]['sumUserNum'] = 1;

                $tmpUserList[$tmpPrivilegeId]['userList'][] = $tmpRow;
                $allMoney += $tmpRow->finish_number * $tmpRow->price;
            }


            //设定的角色不进行统计数量到工序数量中
            //过滤异常数据
            if (!DepartmentUser::getCurrentInfo($tmpRow->uid)) {
                continue;
            }
            $tmpUserInfo = DepartmentUser::getCurrentInfo($tmpRow->uid)->toArray();
            $tmpPrivilegeId = $tmpUserInfo['privilege_id'];
            if (OrderEngine::getProcessNumNoStatistics($tmpPrivilegeId)) {
                continue;
            }


            $finishNum += $tmpRow->finish_number;

            if (!$processIsSum) {//不累加
                if (isset($finishUserNumList[$tmpPrivilegeId])) {
                    $finishUserNumList[$tmpPrivilegeId]['finish_number'] += $tmpRow['finish_number'];
                } else {
                    $finishUserNumList[$tmpPrivilegeId]['finish_number'] = $tmpRow['finish_number'];
                }
            }
        }


        //不累加--未完工时取完成量最小的员工
        if (!empty($finishUserNumList)) {
            $finishMinNum = '';
            foreach ($finishUserNumList as $finishUserNumRow) {
                if ($finishMinNum === 0) {//如果有员工完成数量为0，
                    break;
                }

                if ($finishUserNumRow['finish_number'] < $finishMinNum || $finishMinNum === '') {//如果有员工完成数量更少，或者第一个员工的数据
                    $finishMinNum = $finishUserNumRow['finish_number'];
                }
            }
            $finishNum = $finishMinNum;
        }


        $list = array_values($tmpUserList);


        $isAllowReset = 1;//是否允许重新派单 1-允许 2-不允许
        //如果工单已经开工，不允许再开工
        if ($order_process_info['status'] == 3 || $order_process_info['status'] == 4) {
            $isAllowReset = 2;
        }

        //如果工序管理员不允许重新分派工单
        if ($userId != $order_process_info['uid'] && $userId != $orderinfo['uid']) {
            $isAllowReset = 2;
        }

        //是否显示金额相关的数据 true-隐藏  false-显示
        $isHideMoneyData = OrderEngine::getHideMoneyDataByProcessId($order_process_info['process_type']);

        return compact('processInfoStr', 'isAllowReset', 'orderProcessId', 'finishNum', 'allMoney', 'orderinfo', 'list', 'isHideMoneyData');
    }

    public function info($id)
    {
        $info = Order::where('id', $id)->select([
            'id',
            'order_type',
            'order_title',
            'contract_number',
            'customer_name',
            'product_name',
            'product_num',
            'unit',
            'grammage',
            'chip_specification_length',
            'chip_specification_width',
            'finished_specification',
            'finished_weight',
            'finished_date',
            'created_at',
            'updated_at',
            'weaving_type',
            'plate_numbering',
            'plate_position',
            'plate_modification',
            'public_plate',
            'is_priority',
            'enterprise_icon',
            'production_case_diagram',
            'status',
            'uid',
            'company_id',
            'order_pre_id',
        ])->first();
        $info->create_time = $info->created_at->formatLocalized('%Y-%m-%d %H:%M:%S');
        $info->updated_time = $info->updated_at->formatLocalized('%Y-%m-%d %H:%M:%S');

        $orderTypeInfo = \App\Eloquent\Ygt\OrderType::where('id', $info->order_type)->first();

        //处理图片数据
        $imgIdList = explode(',', $info['production_case_diagram']);
        $exampleImg = '';
        foreach ($imgIdList as $imgId) {
            if (!trim($imgId)) {//过滤空格 图片id应该不会有0
                continue;
            }
            if (!$exampleImg) {//取第一张图作为示例图
                $exampleImg = ImgUpload::getImgUrlById($imgId);
            }
        }

        $info->order_type_imgurl = $exampleImg;
        return $info;
    }


    //获取工单报表信息
    public function getOrderReport()
    {
        $orderReportId = request('order_report_id');

        //获取工单报表关系
        $orderReportRow = OrderReport::where(['id' => $orderReportId])->first();
        $orderId = $orderReportRow['order_id'];
        $orderReportTypeId = $orderReportRow['order_report_type_id'];
        $companyId = $orderReportRow['company_id'];

        $orderRow = Order::where(['id' => $orderId])->first();
        $orderReportTypeRow = OrderReportType::where(['id' => $orderReportTypeId])->first();

        $orerReportContentStr = $orderReportTypeRow['content'];
        $orerReportContentList = explode(',', $orerReportContentStr);

        $reportTitle = $orderReportTypeRow['title'];
        $dataDetail = [];

        if (in_array(1, $orerReportContentList)) {
            $dataDetail[] = [
                'type' => 1,
                'title' => '工单号',
                'value' => $orderRow['order_title']
            ];
        }

        if (in_array(2, $orerReportContentList)) {
            $dataDetail[] = [
                'type' => 1,
                'title' => '客户名称',
                'value' => $orderRow['customer_name']
            ];
        }

        $orerProcessCourseAll = $orderMaterialCourseAll = [];
        if (in_array(3, $orerReportContentList) || in_array(4, $orerReportContentList)) {
            //获取工单工序信息
            $orderProcessList = OrderProcess::where(['order_id' => $orderId, 'company_id' => $companyId])->get();
            foreach ($orderProcessList as $orderProcessRow) {
                $orderProcessId = $orderProcessRow['id'];
                //获取工序工单对应的员工工单
                $orderProcessCourseList = OrderProcessCourse::where(['order_process_id' => $orderProcessId, 'company_id' => $companyId])->get();

                //获取对应的员工材料数据
                foreach ($orderProcessCourseList as $orderProcessCourseRow) {
                    $orerProcessCourseAll[] = $orderProcessCourseRow;

                    if (in_array(4, $orerReportContentList)) {
                        $orderProcessCourseId = $orderProcessCourseRow['id'];
                        $orerProcessCourseMaterialList = OrderMaterialCourse::where(['order_process_course_id' => $orderProcessCourseId, 'company_id' => $companyId])->get();
                        foreach ($orerProcessCourseMaterialList as $orerProcessCourseMaterialRow) {
                            $orderMaterialCourseAll[] = $orerProcessCourseMaterialRow;
                        }
                    }

                }
            }
        }

        //员工收益
        if (in_array(3, $orerReportContentList)) {
            $orerProcessCourseAllDeal = [];
            //统计完成数量
            foreach ($orerProcessCourseAll as $orderProcessCourseRow) {
                $uid = $orderProcessCourseRow['uid'];
                if (isset($orerProcessCourseAllDeal[$uid])) {
                    $orerProcessCourseAllDeal[$uid]['finish_number'] += $orderProcessCourseRow['finish_number'];
                } else {
                    $orerProcessCourseAllDeal[$uid]['finish_number'] = $orderProcessCourseRow['finish_number'];
                    $orerProcessCourseAllDeal[$uid]['uid'] = $uid;
                }
            }
            //获取计件工资数
            $dataList = [];
            foreach ($orerProcessCourseAllDeal as $uid => $orerProcessCourseRow) {
                //获取单件工资
                $userInfo = DepartmentUser::getCurrentInfo($uid)->toArray();

                $dataList[] = [
                    'title' => $userInfo['truename'],
                    'value' => '计件' . $orerProcessCourseRow['finish_number'] . '，' . $userInfo['price'] * $orerProcessCourseRow['finish_number'] . '元'
                ];
            }

            $dataDetail[] = [
                'type' => 2,
                'title' => '员工收益',
                'data' => $dataList
            ];
        }

        //材料损耗
        if (in_array(4, $orerReportContentList)) {
            $orderMaterialCourseAllDeal = [];
            foreach ($orderMaterialCourseAll as $orderMaterialCourseRow) {
                $materialId = $orderMaterialCourseRow['material_id'];
                if (isset($orderMaterialCourseAllDeal[$materialId])) {
                    $orderMaterialCourseAllDeal[$materialId]['receive_number'] += $orderMaterialCourseRow['receive_number'];
                    $orderMaterialCourseAllDeal[$materialId]['scrap_number'] += $orderMaterialCourseRow['scrap_number'];
                    $orderMaterialCourseAllDeal[$materialId]['residual_number'] += $orderMaterialCourseRow['residual_number'];
                } else {
                    $orderMaterialCourseAllDeal[$materialId]['receive_number'] = $orderMaterialCourseRow['receive_number'];
                    $orderMaterialCourseAllDeal[$materialId]['scrap_number'] = $orderMaterialCourseRow['scrap_number'];
                    $orderMaterialCourseAllDeal[$materialId]['residual_number'] = $orderMaterialCourseRow['residual_number'];
                    $orderMaterialCourseAllDeal[$materialId]['material_id'] = $materialId;
                }
            }

            //获取计件工资数
            $dataList = [];
            foreach ($orderMaterialCourseAllDeal as $materialId => $orderMaterialCourseRow) {
                //获取材料信息
                $materialRow = ProductEngine::getProductInfo($materialId)->toArray();
                //废品率
                $wasteRate = (round(($orderMaterialCourseRow['scrap_number'] / ($orderMaterialCourseRow['receive_number'] - $orderMaterialCourseRow['residual_number'])), 4) * 100) . '%';
                //单位
                $unit = $materialRow['unit'];
                if (!$unit) {
                    $unit = '无单位';
                }

                $dataList[] = [
                    'title' => $materialRow['product_name'],
                    'value' => "废品{$orderMaterialCourseRow['scrap_number']}（{$unit}），废品率{$wasteRate}"
                ];
            }

            $dataDetail[] = [
                'type' => 2,
                'title' => '材料损耗',
                'data' => $dataList
            ];
        }

        $data = [
            'report_title' => $reportTitle,
            'dataDetail' => $dataDetail
        ];
        return $data;
    }

    //转变单位名称字段 原因 该字段存值 有三种
    //1单位的id 2单位的名称 3空
    public function changeFieldName23($value = '')
    {
        $result = $value;
        if ($value) {
            $result = Buyers::getNameById($value);
            if (!$result) {
                $result = $value;
            }
        }
        return $result;
    }

    //获取关联工单列表
    public function getRelateOrderList()
    {
        $userId = Func::getHeaderValueByName('userid');

        //判断用户是否为管理员
        $userInfo = DepartmentUser::getCurrentInfo($userId)->toArray();
        $companyId = isset($userInfo['company_id']) ? $userInfo['company_id'] : '';

        $orderList = Order::where([['status','!=',4]])->where(['company_id' => $companyId])->orderBy('id', 'desc')->get()->toArray();

        $newOrderList = [];
        foreach ($orderList as $k => $tmpOrderRow) {
            //获取生产实例图
            $productionCaseDiagramIds = isset($tmpOrderRow['production_case_diagram']) ? $tmpOrderRow['production_case_diagram'] : '';
            if ($productionCaseDiagramIds) {
                $tmpArr = explode(',', $productionCaseDiagramIds);
                $productionCaseDiagramId = reset($tmpArr);
                $productionCaseDiagram = ImgUpload::getImgUrlById($productionCaseDiagramId);
                if (!$productionCaseDiagram) {//未获取到id对应的图片
                    $productionCaseDiagram = env('APP_URL') . '/assets/mobile/common/images/order_list_default.png';
                }

            } else {
                $productionCaseDiagram = env('APP_URL') . '/assets/mobile/common/images/order_list_default.png';
            }


            $tmpOrderRow = \App\Engine\OrderEngine::dealOrderFiled($tmpOrderRow);


            //订单创建时间（派发时间）
            $orderCreateTime = $tmpOrderRow['created_at'];
            if ($orderCreateTime) {
                $orderCreateTime = date('Y-m-d', $orderCreateTime);
            }

            //获取工序类型名称
            $orderTypeTitle = OrderType::getOneValueById($tmpOrderRow['order_type'], 'title');

            $imgId = $tmpOrderRow['production_case_diagram'];

            $orderStatusArr = config('order.order_status_list');
            $orderStatus = $tmpOrderRow['status'];
            if (isset($orderStatusArr[$orderStatus])) {
                $orderStatusStr = $orderStatusArr[$orderStatus]['txt'];
                $statusColor = $orderStatusArr[$orderStatus]['color'];
            } else {
                $orderStatusStr = '';
                $statusColor = 'FFB401';
            }


            $productName = \App\Engine\OrderEngine::getOrderFiledValueTrue($tmpOrderRow['product_name'], 20);
            $tmpDataRow = [
                'customer_title' => '单位名称',//工单列表展示字段
                'product_title' => '品名',//工单列表展示字段
                'order_title' => '单号',//工单列表展示字段
                'customer_name' => isset($tmpOrderRow['field_name_23']) ? $tmpOrderRow['field_name_23'] : '',//新加字段客户
                'product_name' => isset($productName) ? $productName : '',//新加字段品名
                'order_title_value' => $tmpOrderRow['order_title'],//新加字段单号
                'firstPropertyName' => '成品规格',
                'secondPropertyName' => '数量',
                'thirdPropertyName' => '交货日期',
                'thirdPropertyValue' => $tmpOrderRow['finished_date'],
                'secondPropertyValue' => $tmpOrderRow['product_num'],
                'firstPropertyValue' => isset($tmpOrderRow['finished_specification']) ? $tmpOrderRow['finished_specification'] : '',
                'productionCaseDiagram' => $productionCaseDiagram,
                'productOrderTimeValue' => $orderCreateTime,
                'orderTypeTitle' => $orderTypeTitle,
                'orderNumberValue' => $orderTypeTitle,
                'orderTimeValue' => $tmpOrderRow['finished_date'],
                'relate_id' => $tmpOrderRow['id'],
                'orderStatus' => $orderStatusStr,
                'statusColor' => $statusColor,
                'order_type' => $tmpOrderRow['order_type'],
                'img_id' => $imgId,
            ];

            $newOrderList[] = $tmpDataRow;
        }

        return $newOrderList;
    }


    /**
     * Description:测试模块
     * User: zhuyujun
     */
    public function test()
    {
//        $tmpArr = [
//            [
//                'order_process_product_id' => '1',
//                'num_list' => [30,30,40]
//            ]
//        ];
        $tmpArr = [];
        $tmpArr[] = [
            'process_product_id' => 1,
            'number' => 100,
        ];
        $tmpArr[] = [
            'process_product_id' => 2,
            'number' => 150,
        ];

//        echo \GuzzleHttp\json_encode($tmpArr);die();
        print_r($tmpArr);die();

        $tmpWarehouseBillList = \App\Eloquent\Ygt\WarehouseBill::where(['status'=>0])->get();
        foreach($tmpWarehouseBillList as $tmpWarehouseBillRow){
            $tmpWarehouseBillRow->status = 1;
            $tmpWarehouseBillRow->save();
        }

        //待入库列表增加企业ID
        $tmpList = \App\Eloquent\Ygt\OrderFinishedProduct::all();
        foreach($tmpList as $tmpObj){
            $orderId = $tmpObj['order_id'];
            $tmpOrderRow = \App\Eloquent\Ygt\Order::where(['id'=>$orderId])->first();
            $tmpObj->company_id = $tmpOrderRow['company_id'];
            $tmpObj->save();
        }

        die();

        $fd = false;
        if($fd){
            while (!feof($fd)) {
                if (($header = @fgets($fd)) && ($header == "\r\n" || $header == "\n")) {
                    break;
                }
            }
        }

        if($fd) {
            while (!feof($fd)) {
                $gets .= fread($fd, 128);
            }
        }

        die();


        $assemblageMaterialId = 859;//集合材料ID
        \App\Engine\Material::getMaterialField($assemblageMaterialId);
        dd(\App\Engine\Material::getMaterialField(859));

        $str = "{&quot;branch&quot;:{&quot;colourplate&quot;:[{&quot;group&quot;:[],&quot;num&quot;:&quot;1000&quot;}],&quot;fixed_plate&quot;:[{&quot;name&quot;:&quot;黑&quot;,&quot;sort&quot;:&quot;1&quot;},{&quot;name&quot;:&quot;蓝&quot;,&quot;sort&quot;:&quot;2&quot;},{&quot;name&quot;:&quot;红&quot;,&quot;sort&quot;:&quot;3&quot;}],&quot;other_plate&quot;:[{&quot;name&quot;:&quot;&quot;,&quot;num&quot;:&quot;1000&quot;}]},&quot;category_id&quot;:&quot;1&quot;,&quot;plate_id&quot;:&quot;116&quot;,&quot;plate_name&quot;:&quot;1111&quot;}";
        $arr = json_decode(htmlspecialchars_decode($str), true);
        dd($arr);

        $tmpObj = \App\Eloquent\Ygt\Product::firstOrNew(['id'=>429]);
        $tmpObj->number = $tmpObj->number + 123;
        $tmpObj->save();
        die();

//        $v = '1.2';
//        if($v > '1.1.1'){
//            dd(1);
//        }
//        dd(2);
        //
//        $tmpSellerCompanyAll = \App\Eloquent\Ygt\SellerCompany::all();
//        foreach ($tmpSellerCompanyAll  as $tmpSellerCompanyRow){
//            $categoryIdStr = $tmpSellerCompanyRow['main_product'];
//        }
//
//
//        if ($categoryIdStr)
//        {
//            $categoryIdArr      = explode(',', $categoryIdStr);
//            foreach($categoryIdArr as $v)
//            {
//                if(!$v){//过滤空
//                    continue;
//                }
//
//                $categoryModel = new \App\Eloquent\Ygt\Category();
//                $categoryArr    = $categoryModel->getCategoryOption($v,$companyId);
//                $category       = collect($categoryArr);
//                $tempCategoryIds = $category->map(function ($c) {
//                    return $c['id'];
//                })->toArray();
//                $categoryIdArr  = array_merge($categoryIdArr,$tempCategoryIds);
//            }
//
//            $categoryIdArr      = array_unique($categoryIdArr);
//
//            //获取集合材料ID列表
//            $materialIdArr = \App\Eloquent\Ygt\AssemblageMaterial::whereIn('category_id',$categoryIdArr)->get()->pluck('id');
//
//            foreach ($materialIdArr as $materialId){
//                $tmpObj = \App\Eloquent\Ygt\SellerCompanyMaterial::firstOrNew(['seller_company_id'=>$sellerCompanyId,'assemblage_material_id'=>$materialId]);
//                $tmpObj->seller_company_id = $sellerCompanyId;
//                $tmpObj->assemblage_material_id = $materialId;
//                $tmpObj->save();
//            }
//
//            //删除未选择分类下的材料绑定关系
//            \App\Eloquent\Ygt\SellerCompanyMaterial::where(['seller_company_id'=>$sellerCompanyId])->whereNotIn('assemblage_material_id',$materialIdArr)->delete();
//        }





        //获取某权限的用户
        $userId = \App\Engine\Func::getHeaderValueByName('userid');
        $userInfo = \App\Eloquent\Ygt\DepartmentUser::getCurrentInfo($userId)->toArray();
        $companyId = $userInfo['company_id'];

        $privilegeIdList = \App\Engine\OrderEngine::getPrivilegeByNode($companyId, 10);
        if (in_array($userInfo['privilege_id'], $privilegeIdList)) {
            //采购员角色的数据
        }

        $tmpOrderTypeTitle = "二复合袋";//工艺名称
        $tmp1 = "二复合袋•覆膜";
        $re = str_replace([$tmpOrderTypeTitle."•",$tmpOrderTypeTitle],'',$tmp1);
        dd($re);


//        $arr=[
////            [
////                'name' => '1',
////                'sort' => '3',
////            ],
////            [
////                'name' => '2',
////                'sort' => '2',
////            ],
////            [
////                'name' => '3',
////                'sort' => '1',
////            ],
//        ];
//
//
//
//        array_multisort(array_column($arr,'sort'),SORT_ASC,$arr);
//        dd($arr);

//        //脚本:将工艺工单的完成数量存入表字段 completed_number 中
//        $orderProcessList = \App\Eloquent\Ygt\OrderProcess::all();
//        foreach ($orderProcessList as $orderProcessRow){
//            $tmpOrderPorcessCompleteNum = \App\Engine\OrderEngine::getOrderPorcessCompleteNum($orderProcessRow);
//            $orderProcessRow->completed_number = $tmpOrderPorcessCompleteNum;
//            $orderProcessRow->save();
//        }
//        die('操作成功');

//        $arr = [
//        'fixed_plate' => [
//            [
//                'id' => '1',
//                'name' => '黄',
//                'is_choose' => 1,//1-选中，0-未选中
//                'is_delete' => 1,//是否可删除 1-可删除 0-不可删除
//            ],
//            [
//                'id' => '2',
//                'name' => '白',
//                'is_choose' => 0,//1-选中，0-未选中
//                'is_delete' => 0,//是否可删除 1-可删除 0-不可删除
//            ],
//        ],
//        'colourplate'=>[
//            [
//                'id' => '1',
//                'name' => '黄',
//                'is_choose' => 1,//1-选中，0-未选中
//                'is_delete' => 0,//是否可删除 1-可删除 0-不可删除
//                'model' => [
//                    '001','002','003'
//                ],
//            ],
//        ],
//    ];

        $arr = [
            'plate_id' => 1,
            'plate_name' => '电雕版',
            'category_id' => 1,
            'branch' => [
                'fixed_plate' => [
                    [
                        'name' => '白',
                        'sort' => 1,
                    ],
                    [
                        'name' => '黑',
                        'sort' => 2,
                    ],
                ],
                'colourplate' => [
                    [
                        'num' => 100,
                        'group' => [
                            [
                                'name' => '黄',
                                'model' => '001',
                            ],
                            [
                                'name' => '红',
                                'model' => '002',
                            ],
                        ],
                    ],
                    [
                        'num' => 500,
                        'group' => [
                            [
                                'name' => '黄',
                                'model' => '004',
                            ],
                            [
                                'name' => '红',
                                'model' => '010',
                            ],
                        ],
                    ],
                ],
                'other_plate' => [
                    [
                        'name' => '白',
                        'num' => 100,
                    ],
                    [
                        'name' => '黑',
                        'num' => 200,
                    ],
                ],
            ],
        ];

        if(isset($_REQUEST['json']) && $_REQUEST['json']){
            echo json_encode($arr);die();
        }

        echo "<pre>";
        print_r($arr);
        echo "</pre>";
        die();


        //脚本：生成集合材料表数据，并关联与原材料表的数据
        $materialGroupList  = \App\Eloquent\Ygt\Product::all()->groupBy('product_name');
        foreach ($materialGroupList as $productName => $materialList){
            $sunNum = 0;//总数量
            $assemblageMaterialRow = [];
            foreach ($materialList as $materialRow){
                if(empty($assemblageMaterialRow)){
                    $assemblageMaterialRow = $materialRow->toArray();
                    //过滤参数
                    unset($assemblageMaterialRow['supplier_id']);
                    unset($assemblageMaterialRow['is_customer']);
                    unset($assemblageMaterialRow['customer_id']);
                    unset($assemblageMaterialRow['is_seller']);
                    unset($assemblageMaterialRow['seller_company_id']);
                    unset($assemblageMaterialRow['assemblage_material_id']);
                }

                $sunNum += $materialRow['number'];
            }

            $assemblageMaterialRow['number'] = $sunNum;
            $tmpObj = \App\Eloquent\Ygt\AssemblageMaterial::firstOrNew(['id'=>'']);

            $tmpObj->fill($assemblageMaterialRow);
            $tmpObj->save();
            $assemblageMaterialId = $tmpObj->id;

            foreach ($materialList as $materialRow){
                $materialRow->assemblage_material_id = $assemblageMaterialId;
                $materialRow->save();
            }
        }

        //脚本：增加材料字段表相关的集合材料ID
        $productFieldsList = \App\Eloquent\Ygt\ProductFields::all();
        foreach ($productFieldsList as $productFieldsRow){
            $tmpProductId = $productFieldsRow['product_id'];
            $tmpProductRow = \App\Eloquent\Ygt\Product::where(['id'=>$tmpProductId])->first();
            if($tmpProductRow){
                $productFieldsRow->assemblage_material_id = $tmpProductRow['assemblage_material_id'];
                $productFieldsRow->save();
            }
        }

        die('操作成功');



        $msgCpzl = ',克';
        $tmpArr = explode(',',$msgCpzl);
        if(count($tmpArr) == 2){
            if($tmpArr[0]){
                $msgCpzl = $tmpArr[0].$tmpArr[1];
            }else{
                $msgCpzl = '';
            }
        }

        dd($msgCpzl);


        //脚本，处理废品库存列表信息
        $all = \App\Eloquent\Ygt\Waste::all();
        foreach ($all as $tmpRow){
            $relateType = $tmpRow['relate_type'];
            $wasteName = '';
            if($relateType == 2){
                $ordertypeWasteRow = \App\Eloquent\Ygt\OrdertypeProcessWaste::where(['id'=>$tmpRow['relate_id']])->first();
                if($ordertypeWasteRow){
                    $wasteName = $ordertypeWasteRow['title'];
                }else{
                    $ordertypeWasteRow = \App\Eloquent\Ygt\OrdertypeProcessWaste::withTrashed()->where(['id'=>$tmpRow['relate_id']])->first();
                    if($ordertypeWasteRow){
                        $wasteName = $ordertypeWasteRow['title'].'【已删除】';
                    }
                }

                if($wasteName){
                    $tmpRow->waste_name = $wasteName;
                    $tmpRow->save();
                }

            }
        }


        die('success');





        $arr= [
            [
                'material_id'    => '1',
                'number' => '100',
            ],
            [
                'material_id'    => '2',
                'number' => '50.15',
            ],
        ];

        print_r($arr);die();


        $tmpObj = \App\Eloquent\Ygt\OrderMaterial::where([['id','<','4']]);
        $tmpObj->delete();
        die();



        $arr = [
            'supplier_id' => 1,
            'finished_date' => '20180823',
            'remark' => '宜快不宜迟',
            'material_list' => [
                'material_id' => 1,
                'num' => 1,
                'price' => 1,
            ],
        ];

        echo \GuzzleHttp\json_encode($arr);die();

        $addData = [
            'number' => 1,//出库流水数量
            'material_id' => 1,//材料ID
            'company_id' => 1,//企业ID
            'uid' => 1,//用户ID
            'relate_type' => 6,//相关类型，现在可以固定 写2
            'relate_id' => 1,//外键ID，没有相关业务ID，写0
        ];
        $re = \App\Engine\Stock::addOutgoingWater($addData);
        die();


        //添加ygt_order_process_course表order_process_id字段值
        $orderMaterialList = OrderMaterialCourse::all();
        foreach ($orderMaterialList as $orderMaterialRow) {
            //通过order_id和process_type,获取order_process_id
            $tmpObj = \App\Eloquent\Ygt\OrderProcessCourse::where(['id' => $orderMaterialRow['order_process_course_id']])->first();
            if ($tmpObj) {
                $orderMaterialRow->order_process_id = $tmpObj['order_process_id'];
                $orderMaterialRow->save();
            }
        }


        //添加ygt_order_material表order_process_id字段值
        $orderMaterialList = OrderMaterial::all();
        foreach ($orderMaterialList as $orderMaterialRow) {
            //通过order_id和process_type,获取order_process_id
            $tmpObj = \App\Eloquent\Ygt\OrderProcess::where(['order_id' => $orderMaterialRow['order_id'], 'process_type' => $orderMaterialRow['process_type']])->first();

            if ($orderMaterialRow['order_id'] == 587) {
                $tmpObj = \App\Eloquent\Ygt\OrderProcess::where(['order_id' => $orderMaterialRow['order_id'], 'process_type' => $orderMaterialRow['process_type']])->first();
                $queries = \DB::getQueryLog(); // 获取查询日志
            }
            if ($tmpObj) {
                $orderMaterialRow->order_process_id = $tmpObj['id'];
                $orderMaterialRow->save();
            }
        }

        die('操作成功');

        if (!extension_loaded('imagick')) {
            echo '不在';
            die();
        }

        die();

        //客户表如果没有添加者id自动添加
        $customerList = \App\Eloquent\Ygt\Customer::all();
        foreach ($customerList as $customerRow) {
            if (!$customerRow['add_user_id']) {
                $companyId = $customerRow['company_id'];
                //获取该企业下销售员角色
                $appnodeId = 13;
                $privilegeIdList = \App\Eloquent\Ygt\Privilege::getPrivilegeIds($companyId, $appnodeId);
                if (count($privilegeIdList) && $privilegeIdList[0]) {
                    $privilegeId = $privilegeIdList[0];
                    //获取有这个权限的用户
                    $userRow = \App\Eloquent\Ygt\DepartmentUser::where(['company_id' => $companyId, 'privilege_id' => $privilegeId])->first();
                    if ($userRow) {
                        $userId = $userRow['user_id'];
                        $customerRow->add_user_id = $userId;
                        $customerRow->save();
                    }
                }

            }
        }

        die('操作成功');


        $orderProcessCourseId = 721;
        $re = \App\Eloquent\Ygt\OrderProcessCourse::where(['id' => $orderProcessCourseId])->user()->get();
        dd($re);


        dd(OrderEngine::getStaffOrderList(5, '28', '19900712', '20180613'));


        //增加员工分批提交记录时的企业id
        $list = \App\Eloquent\Ygt\OrderProcessCourseGradation::all();
        foreach ($list as $tmpObj) {
            $uid = \App\Eloquent\Ygt\OrderProcessCourse::where(['id' => $tmpObj->order_process_course_id])->first()->uid;
            $tmpObj->uid = $uid;
            $tmpObj->save();
        }

        die('操作成功');


        phpinfo();
        die();


        $companyId = 5;
        $purchasingAgentPrivilegeList = \App\Eloquent\Ygt\Privilege::getPrivilegeIds($companyId, 10);
        dd($purchasingAgentPrivilegeList);

        $a = 1;
        $b = 1;
        $re = isset($a, $b, $c);
        var_dump($re);
        die();


        die();
        \DB::connection()->enableQueryLog(); // 开启查询日志
        $obj = \App\Eloquent\Ygt\CustomerOrder::where(['id' => 1])->where(['id' => 2])->first();
//        $arr = [
//            'order_title' => $obj->order_title.'112233'
//        ];
//        $obj->fill($arr);
//        $obj->save();
        $queries = \DB::getQueryLog(); // 获取查询日志
        dd($queries);
        die();// 即可查看执行的sql，传入的参数等等
        die();


        $arr = [
            [
                'material_id' => 1,
                'num' => 2,
                'price' => 3,
            ]
        ];

        echo \GuzzleHttp\json_encode($arr);
        die();


        OrderEngine::importOrderListRelation();
        die('import success!');


        $result = OrderType::getAllStepsWithDistribution(39);

        //获取工序可分派给工序管理员的列表
        $result->transform(function ($item) {
//            $item->distributionUser = Privilege::getWithDepartmentUser( $item->distribution );
            $distributionUser = DepartmentUser::getWithPrivilege($item->distribution);
            $process_id = $item->process_id;
            $distributionUser->transform(function ($item) use ($process_id) {
                $item->process_id = $process_id;
                $item->ygtUser->avatar = $item->ygtUser->avatar ? Func::getImgUrlById($item->ygtUser->avatar) : asset('upload/appicon/logo.png');
                return $item;
            });
            $item->distributionUser = $distributionUser->toArray();
            return $item;
        });

        dd($result->toArray());

        $tmp = new Request();
        $re = $this->getManagerOrderDetailListNew($tmp);
        dd($re);

        $privilegeIds = PermissionEngine::getStepActionPrivilegeIdsByOrderTypeProcess(39, 8, 3);//1:查看;2:可写;3:分配;4:提交;5:转发;
        dd($privilegeIds->count());
        //获取方法名
//        $orderPreId = 45;
//        $orderModels = new OrderModels();
//        $orderPreRow = $orderModels->getOrderPreInfo($orderPreId);
//        $orderModels->insertOrder($orderPreRow);
    }
}


if (!function_exists('request')) {
    /**
     * Get an instance of the current request or an input item from the request.
     *
     * @param  array|string $key
     * @param  mixed $default
     * @return \Illuminate\Http\Request|string|array
     */
    function request($key = null, $default = null)
    {
        if (is_null($key)) {
            return app('request');
        }

        if (is_array($key)) {
            return app('request')->only($key);
        }

        return data_get(app('request')->all(), $key, $default);
    }
}